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
SuperAnt30/Vge
6,939
src/Vge/World/Chunk/MapChunk.cs
using System; using System.Collections.Generic; namespace Vge.World.Chunk { /// <summary> /// Карта чанков, через регион 5bit, а дальше массив /// </summary> public class MapChunk { // ulong xy = ((ulong)((uint)x >> 5) << 32) | ((uint)y >> 5); // new Vector2i((int)((xy & 0xFFFFFFFF00000000) >> 27), (int)xy << 5); /// <summary> /// Общекк количество элементов /// </summary> public int Count { get; private set; } = 0; /// <summary> /// Оптимизированный поиск чанка, служит для быстрого поиска чанка /// </summary> private readonly Dictionary<ulong, Region> _map = new Dictionary<ulong, Region>(); /// <summary> /// Перерасчитать количество /// </summary> public void RecalculateCount() { Count = 0; foreach (Region region in _map.Values) { Count += region.Count; } } /// <summary> /// Получить список всех чанков /// </summary> public List<IChunkPosition> GetList() { List<IChunkPosition> chunks = new List<IChunkPosition>(); foreach (Region region in _map.Values) { region.AddRegionList(chunks); } return chunks; } /// <summary> /// Добавить /// </summary> public void Add(IChunkPosition value) { int x = value.CurrentChunkX; int y = value.CurrentChunkY; ulong xy = ((ulong)((uint)x >> 5) << 32) | ((uint)y >> 5); if (!_map.ContainsKey(xy)) { _map.Add(xy, new Region()); } if (_map[xy].Set(x, y, value)) { Count++; } } /// <summary> /// Удалить /// </summary> public void Remove(int x, int y) { IChunkPosition chunk = Get(x, y); if (chunk != null) { ulong xy = ((ulong)((uint)x >> 5) << 32) | ((uint)y >> 5); if (_map[xy].Remove(x, y)) { Count--; if (_map[xy].Count == 0) { _map.Remove(xy); } } } } /// <summary> /// Получить чанк с массива /// </summary> public IChunkPosition Get(int x, int y) { ulong xy = ((ulong)((uint)x >> 5) << 32) | ((uint)y >> 5); if (_map.ContainsKey(xy)) { return _map[xy].Get(x, y); } return null; } /// <summary> /// Проверить наличие чанка /// </summary> public bool Contains(IChunkPosition chunk) => Contains(chunk.CurrentChunkX, chunk.CurrentChunkY); /// <summary> /// Проверить наличие чанка /// </summary> public bool Contains(int x, int y) { ulong xy = ((ulong)((uint)x >> 5) << 32) | ((uint)y >> 5); if (_map.ContainsKey(xy)) { return _map[xy].Contains(x, y); } return false; } /// <summary> /// Очистить /// </summary> public void Clear() { _map.Clear(); Count = 0; } /// <summary> /// Получить количество регионов /// </summary> public int RegionCount => _map.Count; /// <summary> /// Сгенерировать массив для отладки /// </summary> public IChunkPosition[] ToArrayDebug() { IChunkPosition[] destinationArray = new IChunkPosition[Count]; int destinationIndex = 0; foreach (Region region in _map.Values) { Array.Copy(region.ToArrayDebug(), 0, destinationArray, destinationIndex, region.Count); destinationIndex += region.Count; } return destinationArray; } public override string ToString() => Count + "|" + RegionCount; /// <summary> /// Отдельные объект с массивом 1024 элемента /// </summary> private class Region { /// <summary> /// Количество значений /// </summary> public int Count { get; private set; } = 0; private readonly IChunkPosition[] _buffer = new IChunkPosition[1024]; /// <summary> /// Проверить наличие чанка /// </summary> public bool Contains(int x, int y) => _buffer[(y & 31) << 5 | (x & 31)] != null; /// <summary> /// Получить чанк /// </summary> public IChunkPosition Get(int x, int y) => _buffer[(y & 31) << 5 | (x & 31)]; /// <summary> /// Добавить чанк, вернёт true если новый /// </summary> public bool Set(int x, int y, IChunkPosition value) { int index = (y & 31) << 5 | (x & 31); if (_buffer[index] == null) { // Создаём Count++; _buffer[index] = value; return true; } // Перезаписываем _buffer[index] = value; return false; } /// <summary> /// Удалить, вернём true если было удаление /// </summary> public bool Remove(int x, int y) { int index = (y & 31) << 5 | (x & 31); if (_buffer[index] != null) { // Удаляем _buffer[index] = null; Count--; return true; } // Нечего удалять return false; } /// <summary> /// Добавить в лист присутствующие чанки /// </summary> public void AddRegionList(List<IChunkPosition> chunks) { for (int i = 0; i < 1024; i++) { if (_buffer[i] != null) chunks.Add(_buffer[i]); } } /// <summary> /// Сгенерировать массив для отладки /// </summary> public IChunkPosition[] ToArrayDebug() { IChunkPosition[] ar = new IChunkPosition[Count]; int index = 0; for (int i = 0; i < 1024; i++) { if (_buffer[i] != null) ar[index++] = _buffer[i]; } return ar; } public override string ToString() => Count.ToString(); } } }
0
0.869848
1
0.869848
game-dev
MEDIA
0.693498
game-dev
0.956387
1
0.956387
miw-upm/IWVG
1,823
doo/src/main/java/ticTacToe/v480/controllers/local/LocalMoveController.java
package ticTacToe.v480.controllers.local; import ticTacToe.v480.controllers.ColocateControllerVisitor; import ticTacToe.v480.controllers.MoveController; import ticTacToe.v480.controllers.OperationControllerVisitor; import ticTacToe.v480.controllers.errors.ErrorGeneratorType; import ticTacToe.v480.controllers.errors.ErrorReport; import ticTacToe.v480.models.Coordinate; import ticTacToe.v480.models.Game; public class LocalMoveController extends LocalColocateController implements MoveController { private Coordinate origin; LocalMoveController(Game game, LocalCoordinateController coordinateController) { super(game, coordinateController); } @Override public void remove(Coordinate origin) { assert origin != null; assert this.validateOrigin(origin) == null; this.origin = origin; super.remove(origin); } public ErrorReport validateOrigin(Coordinate origin) { assert origin != null; if (!this.full(origin)) { return ErrorGeneratorType.NOT_PROPERTY.getErrorReport(this.getGame()); } return null; } @Override public void put(Coordinate target) { assert target != null; assert origin != null; assert this.validateTarget(origin, target) == null; super.put(target); origin = null; } public ErrorReport validateTarget(Coordinate origin, Coordinate target) { ErrorReport errorReport = super.validateTarget(target); if (errorReport != null) { return errorReport; } if (origin.equals(target)) { return ErrorGeneratorType.REPEATED_COORDINATE.getErrorReport(this.getGame()); } return null; } @Override public void accept(OperationControllerVisitor operationControllerVisitor) { operationControllerVisitor.visit(this); } @Override public void accept(ColocateControllerVisitor colocateControllerVisitor) { colocateControllerVisitor.visit(this); } }
0
0.854659
1
0.854659
game-dev
MEDIA
0.885136
game-dev
0.655284
1
0.655284
ProjectEQ/projecteqquests
5,708
tox/38016.pl
#right skeleton # items: 62829, 62828, 13894, 9304, 12195, 13073, 13074 my $success; sub EVENT_SAY { if ($class eq "Druid") { if ($text=~/animated heads/i) { quest::say("Heh, so you've heard of that, have you. Too funny if you ask me. Who would [" . quest::saylink("i want to animate a skull",false,"want") . "] to animate a skull? Darn things can't do any useful work. They can't even talk!"); quest::settimer("d1",2); } if ($text=~/animate a skull/i) { quest::say("That's rich!"); quest::settimer("d2",2); } if ($text=~/song/i) { quest::say("Yo ho. No sun!!"); quest::say("A skeleton's day is never done."); } if ($text=~/i will do it/i) { quest::say("Ya better hold this."); $client->SummonItem(62829); # Item: Worthless Mining Pick quest::settimer("pathback",1200); quest::moveto(-317.17,-2532.23,-41.15,0,1); quest::depop_withtimer(38017); quest::settimer("movetwo",12); $questclient = $name; $success = 0; #tell heretic pet i've started $start = $entity_list->GetMobByNpcTypeID(38139); $moving = $start->CastToNPC(); $moving->SignalNPC(5); } } } sub EVENT_TIMER { if ($timer eq "pathback") { quest::stoptimer("pathback"); quest::moveto(-294.16,-2356.42,-41.28,0,1); quest::settimer("pathbacktwo",25); } if ($timer eq "pathbacktwo") { quest::stoptimer("pathbacktwo"); quest::moveto(-317.17,-2532.23,-41.15,0,1); quest::settimer("pathbackthree",18); } if ($timer eq "pathbackthree") { quest::stoptimer("pathbackthree"); quest::moveto(-389,-2577,-41.15,0,1); if ($success) { quest::settimer("giveitem",12); $success=0; } } if ($timer eq "giveitem") { quest::stoptimer("giveitem"); quest::say("Well, you somehow managed to not piss off the heretic pet and you sang the song often enough, though I don't think your heart was in it. Here's the scroll you wanted. Of course an animated head just moves around. Without a soul in it, it's pretty worthless."); $entity_list->GetClientByName("$questclient")->SummonItem(62828); #Animating Heads } if ($timer eq "movetwo") { quest::stoptimer("movetwo"); quest::moveto(-294.16,-2356.42,-41.28,0,1); quest::settimer("movethree",20); } if ($timer eq "movethree") { quest::stoptimer("movethree"); quest::moveto(-505.35,-2400,-45.64,0,1); } if ($timer eq "d1") { quest::stoptimer("d1"); quest::say("Don't you have some living person you can annoy?"); } if ($timer eq "d2") { quest::stoptimer("d2"); quest::say("You actually WANT that spell? You do know that, so far anyway, only Elia has been able to cast it, right? Not that anyone's trying all that hard. Besides, what could you possibly offer us to get you a copy of the scroll? Nothing, that's what."); quest::settimer("d3",2); } if ($timer eq "d3") { quest::stoptimer("d3"); quest::say("Hold on there, pal. There's bound to be something that we can get from this. . . druid. Let me think about it for a minute."); quest::settimer("d4",2); } if ($timer eq "d4") { quest::stoptimer("d4"); quest::say("Hah!"); quest::settimer("d5",2); } if ($timer eq "d5") { quest::stoptimer("d5"); quest::say("Friend, your mind was devoured by maggots years ago. You couldn't think you way out of this tunnel if your unlife depended on it."); quest::settimer("d6",2); } if ($timer eq "d6") { quest::stoptimer("d6"); quest::say("Shut your trap already. After the centuries that we've been working here, side by side, you'd think that by now you'd have run out of stupid things to say."); quest::settimer("d7",2); } if ($timer eq "d7") { quest::stoptimer("d7"); quest::say("Hang on, that's it! Look around you, this place is spotless and yet they make us pretend to clean up and poke at the rocks like we're doing something useful. We just want to take a break for a few hours, wander down to the beach, scare someone, maybe even feast on someone's bones or something. That's not askin' too much, is it? All you gotta do is stand here with a pick and tell that idiot heretic pet that you are on the job."); quest::settimer("d8",2); } if ($timer eq "d8") { quest::stoptimer("d8"); quest::say("Oh, and ya gotta sing the song."); quest::settimer("d9",2); } if ($timer eq "d9") { quest::stoptimer("d9"); quest::say("Yah, ya gotta sing the [" . quest::saylink("song") . "]. Stand right were I am and sing it a lot. If you do that, we'll get a copy of that stupid spell for ya, for all the good it will do. So [" . quest::saylink("i will do it", false, "will you do it") . "]? We don't have all day to wait for... oh, well, yeah, I guess we do."); } if ($timer eq "d10") { quest::stoptimer("d10"); quest::say("We will speed up when you return our mining caps. There are falling rocks all over this place!! We could get killed!!"); } } sub EVENT_SIGNAL { if ($signal == 1) { quest::settimer("pathback",1); $success = 1; } if ($signal == 9) { quest::say("We are not your pets!!"); quest::settimer("d10",2); } } sub EVENT_ITEM { if (plugin::check_handin(\%itemcount, 13894 => 1)) { quest::say("Aye.. You cut out the middleman.. I shall reward you.. hmm.. I have not found anything. how about.. <CRACK!! SNAP!! RIPP!!> How about something off meself?"); quest::summonitem(quest::ChooseRandom(9304,12195,13073,13074)); # Item(s): Bone Shield (9304), Fractured Femur (12195), Bone Chips (13073), Zombie Skin (13074) } plugin::return_items(\%itemcount); } #END of FILE Zone:tox ID:38016 -- a_skeleton
0
0.929542
1
0.929542
game-dev
MEDIA
0.990823
game-dev
0.970237
1
0.970237
p-org/P
11,160
Src/PCompiler/CompilerCore/TypeChecker/MachineChecker.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Antlr4.Runtime; using Plang.Compiler.TypeChecker.AST.Declarations; using Plang.Compiler.TypeChecker.AST.States; using Plang.Compiler.TypeChecker.Types; namespace Plang.Compiler.TypeChecker { public static class MachineChecker { public static void Validate(ITranslationErrorHandler handler, Machine machine, ICompilerConfiguration job, Scope gScope) { // before validating the machines, lets set the constructor types for machines and interfaces if(!machine.IsSpec) InitializeContructorType(handler, machine, gScope); ValidateHandlers(handler, machine); ValidateTransitions(handler, machine); // special validation for monitors: // ensure that each event handler is in the observe set. ValidateSpecObservesList(handler, machine, job); } private static void InitializeContructorType(ITranslationErrorHandler handler, Machine machine, Scope gScope) { var startState = FindStartState(machine, handler); machine.PayloadType = GetStatePayload(startState); gScope.Get(machine.Name, out Interface @interface); @interface.PayloadType = machine.PayloadType; } private static void ValidateSpecObservesList(ITranslationErrorHandler handler, Machine machine, ICompilerConfiguration job) { if (machine.IsSpec) { foreach (var state in machine.AllStates()) { foreach (var pair in state.AllEventHandlers) { if (!machine.Observes.Events.Contains(pair.Key)) { job.Output.WriteWarning( handler.SpecObservesSetIncompleteWarning(pair.Value.SourceLocation, pair.Key, machine)); } } } } } private static void ValidateHandlers(ITranslationErrorHandler handler, Machine machine) { foreach (var state in machine.AllStates()) { if (state.Entry?.Signature.Parameters.Count > 1) { throw handler.MoreThanOneParameterForHandlers(state.SourceLocation, state.Entry.Signature.Parameters.Count); } if (state.Exit?.Signature.Parameters.Count > 0) { throw handler.ExitFunctionCannotTakeParameters(state.SourceLocation, state.Exit.Signature.Parameters.Count); } foreach (var pair in state.AllEventHandlers) { var handledEvent = pair.Key; switch (pair.Value) { case EventDoAction eventDoAction: if (eventDoAction.Target != null && eventDoAction.Target.Signature.ParameterTypes.Count() > 1) { throw handler.MoreThanOneParameterForHandlers(eventDoAction.SourceLocation, eventDoAction.Target.Signature.ParameterTypes.Count()); } break; case EventGotoState eventGotoState: if (eventGotoState.TransitionFunction != null && eventGotoState.TransitionFunction.Signature.ParameterTypes.Count() > 1) { throw handler.MoreThanOneParameterForHandlers(eventGotoState.SourceLocation, eventGotoState.TransitionFunction.Signature.ParameterTypes.Count()); } break; case EventDefer _: case EventIgnore _: { break; } } } } } public static void ValidateNoStaticHandlers(ITranslationErrorHandler handler, Machine machine) { foreach (var state in machine.AllStates()) { var illegalUsage = state.Entry != null && IsStaticOrForeign(state.Entry); if (illegalUsage) { throw handler.StaticFunctionNotAllowedAsHandler(state.SourceLocation, state.Entry.Name); } illegalUsage = state.Exit != null && IsStaticOrForeign(state.Exit); if (illegalUsage) { throw handler.StaticFunctionNotAllowedAsHandler(state.SourceLocation, state.Exit.Name); } foreach (var pair in state.AllEventHandlers) { switch (pair.Value) { case EventDoAction eventDoAction: if (eventDoAction.Target != null && IsStaticOrForeign(eventDoAction.Target)) { throw handler.StaticFunctionNotAllowedAsHandler(eventDoAction.SourceLocation, eventDoAction.Target.Name); } break; case EventGotoState eventGotoState: if (eventGotoState.TransitionFunction != null && IsStaticOrForeign(eventGotoState.TransitionFunction)) { throw handler.StaticFunctionNotAllowedAsHandler(eventGotoState.SourceLocation, eventGotoState.TransitionFunction.Name); } break; case EventDefer _: case EventIgnore _: break; default: throw handler.InternalError(pair.Value.SourceLocation, new Exception("Unknown transition type parsed, report to the P team")); } } } } private static bool IsStaticOrForeign(Function function) { return function.Owner == null || function.IsForeign; } private static void ValidateTransitions(ITranslationErrorHandler handler, Machine machine) { foreach (var state in machine.AllStates()) { foreach (var pair in state.AllEventHandlers) { var handledEvent = pair.Key; switch (pair.Value) { case EventDoAction eventDoAction: if (eventDoAction.Target != null) { ValidateEventPayloadToTransitionTarget(handler: handler, sourceLocation: eventDoAction.SourceLocation, eventPayloadType: handledEvent.PayloadType, targetFunction: eventDoAction.Target); } break; case EventGotoState eventGotoState: if (eventGotoState.Target.Entry != null) { ValidateEventPayloadToTransitionTarget(handler: handler, sourceLocation: eventGotoState.SourceLocation, eventPayloadType: handledEvent.PayloadType, targetFunction: eventGotoState.Target.Entry); } if (eventGotoState.TransitionFunction != null) { ValidateEventPayloadToTransitionTarget(handler: handler, sourceLocation: eventGotoState.SourceLocation, eventPayloadType: handledEvent.PayloadType, targetFunction: eventGotoState.TransitionFunction); } break; case EventDefer _: case EventIgnore _: { break; } } } } } private static void ValidateEventPayloadToTransitionTarget(ITranslationErrorHandler handler, ParserRuleContext sourceLocation, PLanguageType eventPayloadType, Function targetFunction) { IReadOnlyList<PLanguageType> entrySignature = targetFunction.Signature.ParameterTypes.ToList(); if (entrySignature.Count == 0) { return; } if (entrySignature.Count > 1) { throw handler.InternalError(sourceLocation, new Exception("Target function cannot have multiple parameters (report this to the P developers)")); } if (entrySignature.Count == 1 && entrySignature[0].IsAssignableFrom(eventPayloadType)) { return; } if (entrySignature.Count == 1 && eventPayloadType.Canonicalize() is TupleType tuple && tuple.Types.Count == 1 && entrySignature[0].IsAssignableFrom(tuple.Types[0])) { return; } if (entrySignature.Count == 1) { throw handler.TypeMismatch(sourceLocation, eventPayloadType, entrySignature[0]); } PLanguageType entrySignatureType = new TupleType(entrySignature.ToArray()); if (!entrySignatureType.IsAssignableFrom(eventPayloadType)) { throw handler.TypeMismatch(sourceLocation, eventPayloadType, entrySignatureType); } } private static PLanguageType GetStatePayload(State startState) { return startState.Entry?.Signature.Parameters.ElementAtOrDefault(0)?.Type ?? PrimitiveType.Null; } private static State FindStartState(Machine machine, ITranslationErrorHandler handler) { var foundStartState = false; foreach (var state in machine.AllStates()) { if (state == machine.StartState || state.IsStart) { if (!foundStartState) { foundStartState = true; } else { throw handler.TwoStartStates(machine, state); } } } Debug.Assert(!(foundStartState && machine.StartState == null), "machine has unregistered start state"); if (!foundStartState || machine.StartState == null) { throw handler.MissingStartState(machine); } return machine.StartState; } } }
0
0.911825
1
0.911825
game-dev
MEDIA
0.435998
game-dev
0.88928
1
0.88928
qq576067421/Fishing
1,142
Client/Assets/Plugins/Fishing.Common/TableData/TbDataOperateType.cs
using System; using System.Collections.Generic; using GF.Common; public class TbDataOperateType : EbData { //------------------------------------------------------------------------- public _eOperateType OperateType { get; private set; } public string OperateName { get; private set; } public int OperateEffectId { get; private set; } public bool IsCompandType { get; private set; } //------------------------------------------------------------------------- public override void load(EbPropSet prop_set) { OperateType = (_eOperateType)Id; OperateName = prop_set.getPropString("T_OperateName").get(); OperateEffectId = prop_set.getPropInt("I_EffectId").get(); IsCompandType = prop_set.getPropInt("I_IsCompandType").get() == 1 ? true : false; } } //------------------------------------------------------------------------- public enum _eOperateType { None = 0, Enhance, Decompose, Compound, Split, Sell, Market, Auction, UpRank, Upgrade, Forget, Learn, Inset, Takeon, Takeoff, Use, Repair, Choose }
0
0.551073
1
0.551073
game-dev
MEDIA
0.339412
game-dev
0.510037
1
0.510037
DichuuCraft/SReplay
2,193
src/main/java/com/hadroncfy/sreplay/config/AbstractTextRenderer.java
package com.hadroncfy.sreplay.config; import net.minecraft.text.ClickEvent; import net.minecraft.text.HoverEvent; import net.minecraft.text.LiteralText; import net.minecraft.text.MutableText; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.text.HoverEvent.Action; public abstract class AbstractTextRenderer<C> { protected abstract MutableText renderString(String s); public Text render(C ctx, Text template) { MutableText ret; if (template instanceof LiteralText) { ret = renderString(((LiteralText) template).getRawString()); } else if (template instanceof TranslatableText) { final TranslatableText tc = (TranslatableText) template; Object[] args = new Object[tc.getArgs().length]; for (int i = 0; i < args.length; i++) { Object obj = tc.getArgs()[i]; if (obj instanceof Text) { obj = render(ctx, (Text) obj); } else { obj = "null"; } args[i] = obj; } ret = new TranslatableText(tc.getKey(), args); } else { ret = template.copy(); } ret.setStyle(renderStyle(ctx, template.getStyle())); for (Text t : template.getSiblings()) { ret.append(render(ctx, t)); } return ret; } private Style renderStyle(C ctx, /* mut */ Style style) { HoverEvent h = style.getHoverEvent(); if (h != null && h.getAction() == HoverEvent.Action.SHOW_TEXT) { Text action = h.getValue(HoverEvent.Action.SHOW_TEXT); style = style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, render(ctx, action))); } ClickEvent c = style.getClickEvent(); if (c != null){ style = style.withClickEvent(new ClickEvent(c.getAction(), renderString(c.getValue()).asString())); } String i = style.getInsertion(); if (i != null){ style = style.withInsertion(renderString(i).asString()); } return style; } }
0
0.600585
1
0.600585
game-dev
MEDIA
0.892373
game-dev
0.917978
1
0.917978
collinsmith/riiablo
20,178
core/src/main/java/com/riiablo/save/CharData.java
package com.riiablo.save; import java.nio.ByteBuffer; import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.ToStringBuilder; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.IntIntMap; import com.badlogic.gdx.utils.Pool; import com.riiablo.CharacterClass; import com.riiablo.Riiablo; import com.riiablo.attributes.Attributes; import com.riiablo.attributes.Stat; import com.riiablo.attributes.StatListReader; import com.riiablo.attributes.StatListRef; import com.riiablo.attributes.StatRef; import com.riiablo.codec.excel.DifficultyLevels; import com.riiablo.io.ByteInput; import com.riiablo.item.BodyLoc; import com.riiablo.item.Item; import com.riiablo.item.ItemReader; import com.riiablo.item.Location; import com.riiablo.item.StoreLoc; import com.riiablo.item.Type; import com.riiablo.skill.SkillCodes; import com.riiablo.util.BufferUtils; // TODO: support pooling CharData for multiplayer public class CharData implements ItemData.UpdateListener, Pool.Poolable { private static final String TAG = "CharData"; private static final boolean DEBUG = true; private static final boolean DEBUG_ITEMS = DEBUG && !true; private static final IntIntMap defaultSkills = new IntIntMap(); static { defaultSkills.put(SkillCodes.attack, 1); defaultSkills.put(SkillCodes.kick, 1); //defaultSkills.put(SkillCodes.throw_, 1); defaultSkills.put(SkillCodes.unsummon, 1); //defaultSkills.put(SkillCodes.left_hand_throw, 1); defaultSkills.put(SkillCodes.left_hand_swing, 1); } public String name; public byte charClass; public int flags; public byte level; public final int hotkeys[] = new int[D2S.NUM_HOTKEYS]; public final int actions[][] = new int[D2S.NUM_ACTIONS][D2S.NUM_BUTTONS]; public final byte towns[] = new byte[D2S.NUM_DIFFS]; public int mapSeed; public final byte realmData[] = new byte[144]; final MercData mercData = new MercData(); final short questData[][][] = new short[Riiablo.NUM_DIFFS][Riiablo.NUM_ACTS][8]; final int waypointData[][] = new int[Riiablo.NUM_DIFFS][Riiablo.NUM_ACTS]; final long npcIntroData[] = new long[Riiablo.NUM_DIFFS]; final long npcReturnData[] = new long[Riiablo.NUM_DIFFS]; final Attributes statData = Attributes.obtainLarge(); final IntIntMap skillData = new IntIntMap(); final ItemData itemData = new ItemData(statData, null); Item golemItemData; public int diff; public boolean managed; public CharacterClass classId; final IntIntMap skills = new IntIntMap(); final Array<StatRef> chargedSkills = new Array<>(false, 16); final Array<SkillListener> skillListeners = new Array<>(false, 16); @Deprecated private static final ItemReader ITEM_READER = new ItemReader(); // TODO: inject @Deprecated private static final StatListReader STAT_READER = new StatListReader(); // TODO: inject /** Constructs a managed instance. Used for local players with complete save data */ public static CharData loadFromD2S(int diff, D2S d2s) { return new CharData().set(diff, true).load(d2s); } /** Constructs an unmanaged instance. Used for remote players with complete save data. */ @SuppressWarnings("deprecation") // d2s writer not implemented yet -- stub deprecated to avoid usage public static CharData loadFromBuffer(int diff, ByteBuffer buffer) { byte[] bytes = BufferUtils.readRemaining(buffer); ByteInput in = ByteInput.wrap(bytes); D2S d2s = D2SReader.INSTANCE.readD2S(in); D2SReader.INSTANCE.readRemaining(d2s, in, STAT_READER, ITEM_READER); D2SWriterStub.put(d2s, bytes); return new CharData().set(diff, false).load(d2s); } /** * @param managed whether or not this data is backed by a file */ public static CharData obtain(int diff, boolean managed, String name, byte charClass) { return obtain().set(diff, managed, name, charClass); } /** Constructs an uninitialized CharData -- must be initialized via #set */ public static CharData obtain() { return new CharData(); } /** Constructs an unmanaged instance. Used for remote players with only partial save data. */ public static CharData createRemote(String name, byte charClass) { return new CharData().set(Riiablo.NORMAL, false, name, charClass); } @Override public String toString() { return new ToStringBuilder(this).append(name).append(classId).append("level", level).build(); } public CharData set(int diff, boolean managed) { this.diff = diff; this.managed = managed; return this; } public CharData set(int diff, boolean managed, String name, byte charClass) { set(diff, managed); this.name = name; this.charClass = charClass; classId = CharacterClass.get(charClass); flags = D2S.FLAG_EXPANSION; level = 1; Arrays.fill(hotkeys, D2S.HOTKEY_UNASSIGNED); for (int[] actions : actions) Arrays.fill(actions, 0); // TODO: check and set town against saved town mapSeed = 0; return this; } CharData() {} public CharData clear() { reset(); return this; } public CharData load(D2S d2s) { /** * FIXME: designed to call {@link D2SReader#readRemaining} on local clients * because they will only have had their headers loaded. This is a * problem because network clients already have their remaining data * loaded, and this method shouldn't have access to the remaining * bytes. */ managed = true; if (!d2s.bodyRead()) { // FIXME: workaround -- D2GS doesn't have D2S files, but will when authoritative byte[] data = D2SWriterStub.getBytes(d2s.name); assert data != null : "d2s.bodyRead(" + d2s.bodyRead() + ") but data == null"; ByteInput in = ByteInput.wrap(data); in.skipBytes(D2SReader96.HEADER_SIZE); D2SReader.INSTANCE.readRemaining(d2s, in, STAT_READER, ITEM_READER); } D2SReader.INSTANCE.copyTo(d2s, this); preprocessItems(); itemData.addUpdateListener(this); return this; } private void preprocessItems() { itemData.preprocessItems(); mercData.itemData.preprocessItems(); } @Override public void reset() { softReset(); name = null; charClass = -1; classId = null; flags = 0; level = 0; Arrays.fill(hotkeys, D2S.HOTKEY_UNASSIGNED); for (int i = 0, s = D2S.NUM_ACTIONS; i < s; i++) Arrays.fill(actions[i], 0); Arrays.fill(towns, (byte) 0); mapSeed = 0; Arrays.fill(realmData, (byte) 0); mercData.flags = 0; mercData.seed = 0; mercData.name = 0; mercData.type = 0; mercData.xp = 0; for (int i = 0, i0 = Riiablo.NUM_DIFFS; i < i0; i++) { for (int a = 0; a < Riiablo.NUM_ACTS; a++) Arrays.fill(questData[i][a], (short) 0); Arrays.fill(waypointData[i], 0); npcIntroData[i] = 0; npcReturnData[i] = 0; } } void softReset() { statData.base().clear(); statData.reset(); skillData.clear(); itemData.clear(); mercData.statData.base().clear(); mercData.statData.reset(); mercData.itemData.clear(); golemItemData = null; skills.clear(); chargedSkills.clear(); skillListeners.clear(); DifficultyLevels.Entry diff = Riiablo.files.DifficultyLevels.get(this.diff); StatListRef base = statData.base(); base.put(Stat.strength, 0); base.put(Stat.energy, 0); base.put(Stat.dexterity, 0); base.put(Stat.vitality, 0); base.put(Stat.statpts, 0); base.put(Stat.newskills, 0); base.put(Stat.hitpoints, 0); base.put(Stat.maxhp, 0); base.put(Stat.mana, 0); base.put(Stat.maxmana, 0); base.put(Stat.stamina, 0); base.put(Stat.maxstamina, 0); base.put(Stat.level, 0); base.put(Stat.experience, 0); base.put(Stat.gold, 0); base.put(Stat.goldbank, 0); base.put(Stat.armorclass, 0); base.put(Stat.damageresist, 0); base.put(Stat.magicresist, 0); base.put(Stat.fireresist, diff.ResistPenalty); base.put(Stat.lightresist, diff.ResistPenalty); base.put(Stat.coldresist, diff.ResistPenalty); base.put(Stat.poisonresist, diff.ResistPenalty); base.put(Stat.maxfireresist, 75); base.put(Stat.maxlightresist, 75); base.put(Stat.maxcoldresist, 75); base.put(Stat.maxpoisonresist, 75); // TODO: set base merc stats based on hireling tables and level base = mercData.statData.base(); base.put(Stat.strength, 0); base.put(Stat.energy, 0); base.put(Stat.dexterity, 0); base.put(Stat.vitality, 0); base.put(Stat.statpts, 0); base.put(Stat.newskills, 0); base.put(Stat.hitpoints, 0); base.put(Stat.maxhp, 0); base.put(Stat.mana, 0); base.put(Stat.maxmana, 0); base.put(Stat.stamina, 0); base.put(Stat.maxstamina, 0); base.put(Stat.level, 0); base.put(Stat.experience, 0); base.put(Stat.gold, 0); base.put(Stat.goldbank, 0); base.put(Stat.armorclass, 0); base.put(Stat.damageresist, 0); base.put(Stat.magicresist, 0); base.put(Stat.fireresist, diff.ResistPenalty); base.put(Stat.lightresist, diff.ResistPenalty); base.put(Stat.coldresist, diff.ResistPenalty); base.put(Stat.poisonresist, diff.ResistPenalty); base.put(Stat.maxfireresist, 75); base.put(Stat.maxlightresist, 75); base.put(Stat.maxcoldresist, 75); base.put(Stat.maxpoisonresist, 75); } public void preloadItems() { itemData.load(); mercData.itemData.load(); } public boolean isManaged() { return managed; } public byte[] serialize() { /** TODO: replace this code when {@link D2SWriter} is implemented */ Validate.isTrue(isManaged(), "Cannot serialize unmanaged data"); return D2SWriterStub.getBytes(name); } public int getHotkey(int button, int skill) { return ArrayUtils.indexOf(hotkeys, button == Input.Buttons.LEFT ? skill | D2S.HOTKEY_LEFT_MASK : skill); } public void setHotkey(int button, int skill, int index) { hotkeys[index] = button == Input.Buttons.LEFT ? skill | D2S.HOTKEY_LEFT_MASK : skill; } public int getAction(int button) { return getAction(itemData.alternate, button); } public int getAction(int alternate, int button) { return actions[alternate][button]; } public void setAction(int button, int skill) { setAction(itemData.alternate, button, skill); } public void setAction(int alternate, int button, int skill) { actions[alternate][button] = skill; } public boolean hasMerc() { return mercData.seed != 0; } public MercData getMerc() { return mercData; } public short[] getQuests(int act) { return questData[diff][act]; } public int getWaypoints(int act) { return waypointData[diff][act]; } public long getNpcIntro() { return npcIntroData[diff]; } public long getNpcReturn() { return npcReturnData[diff]; } public boolean hasGolemItem() { return golemItemData != null; } public Item getGolemItem() { return golemItemData; } public Attributes getStats() { return statData; } public void update() { onUpdated(itemData); } @Override public void onUpdated(ItemData itemData) { assert itemData.stats == statData; // FIXME: This corrects a mismatch between max and current, algorithm should be tested later for correctness in other cases statData.set(Stat.stamina, Stat.maxstamina); statData.set(Stat.hitpoints, Stat.maxhp); statData.set(Stat.mana, Stat.maxmana); // This appears to be hard-coded in the original client int dex = statData.get(Stat.dexterity).asInt(); StatRef armorclass = statData.get(Stat.armorclass); armorclass.add(dex / 4); armorclass.forceUnmodified(); skills.clear(); skills.putAll(skillData); skills.putAll(defaultSkills); Item LARM = itemData.getEquipped(BodyLoc.LARM); Item RARM = itemData.getEquipped(BodyLoc.RARM); if ((LARM != null && LARM.typeEntry.Throwable) || (RARM != null && RARM.typeEntry.Throwable)) { skills.put(SkillCodes.throw_, 1); if (classId == CharacterClass.BARBARIAN) { skills.put(SkillCodes.left_hand_throw, 1); } } IntArray inventoryItems = itemData.getStore(StoreLoc.INVENTORY); int[] cache = inventoryItems.items; for (int i = 0, s = inventoryItems.size, j; i < s; i++) { j = cache[i]; Item item = itemData.getItem(j); if (item.type.is(Type.BOOK) || item.type.is(Type.SCRO)) { if (item.base.code.equalsIgnoreCase("ibk")) { skills.getAndIncrement(SkillCodes.book_of_identify, 0, item.attrs.get(Stat.quantity).asInt()); } else if (item.base.code.equalsIgnoreCase("isc")) { skills.getAndIncrement(SkillCodes.scroll_of_identify, 0, 1); } else if (item.base.code.equalsIgnoreCase("tbk")) { skills.getAndIncrement(SkillCodes.book_of_townportal, 0, item.attrs.get(Stat.quantity).asInt()); } else if (item.base.code.equalsIgnoreCase("tsc")) { skills.getAndIncrement(SkillCodes.scroll_of_townportal, 0, 1); } } } chargedSkills.clear(); for (StatRef stat : statData.remaining()) { switch (stat.id()) { case Stat.item_nonclassskill: skills.getAndIncrement(stat.encodedParams(), 0, stat.asInt()); break; case Stat.item_charged_skill: chargedSkills.add(stat.copy()); break; default: // do nothing } } notifySkillChanged(skills, chargedSkills); } public int getSkill(int skill) { return skills.get(skill, 0); } public ItemData getItems() { return itemData; } // @Override public void groundToCursor(Item item) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "groundToCursor " + item); itemData.pickup(item); } // @Override public void cursorToGround() { if (DEBUG_ITEMS) Gdx.app.log(TAG, "cursorToGround"); itemData.drop(); } public void itemToCursor(int i) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "itemToCursor " + i); itemData.pickup(i); } // @Override public void storeToCursor(int i) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "storeToCursor " + i); itemToCursor(i); } // @Override public void cursorToStore(StoreLoc storeLoc, int x, int y) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "cursorToStore " + storeLoc + "," + x + "," + y); itemData.storeCursor(storeLoc, x, y); } // @Override public void swapStoreItem(int i, StoreLoc storeLoc, int x, int y) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "swapStoreItem " + i + "," + storeLoc + "," + x + "," + y); cursorToStore(storeLoc, x, y); storeToCursor(i); } public void bodyToCursor(BodyLoc bodyLoc) { bodyToCursor(bodyLoc, false); } public void cursorToBody(BodyLoc bodyLoc) { cursorToBody(bodyLoc, false); } public void swapBodyItem(BodyLoc bodyLoc) { swapBodyItem(bodyLoc, false); } // @Override public void bodyToCursor(BodyLoc bodyLoc, boolean merc) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "bodyToCursor " + bodyLoc + "," + (merc ? "merc" : "player")); assert itemData.cursor == ItemData.INVALID_ITEM; Item item; if (merc) { int i = mercData.itemData.unequip(bodyLoc); itemData.cursor = itemData.add(item = mercData.itemData.remove(i)); } else { itemData.cursor = itemData.unequip(bodyLoc); item = itemData.getItem(itemData.cursor); } itemData.setLocation(item, Location.CURSOR); } // @Override public void cursorToBody(BodyLoc bodyLoc, boolean merc) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "cursorToBody " + bodyLoc + "," + (merc ? "merc" : "player")); assert itemData.cursor != ItemData.INVALID_ITEM; if (merc) { Item item = itemData.getItem(itemData.cursor); itemData.remove(itemData.cursor); mercData.itemData.equip(bodyLoc, item); } else { itemData.equip(bodyLoc, itemData.cursor); } itemData.cursor = ItemData.INVALID_ITEM; } /** * FIXME: originally worked as an aggregate call on {@link #cursorToBody(BodyLoc, boolean)} and * {@link #bodyToCursor(BodyLoc, boolean)}, and while that worked fine programically to * pass the assertions within {@link ItemData}, {@link ItemData.LocationListener#onChanged} * was being called out of order for setting the cursor, causing the cursor to be unset * within the UI immediately after being changed. */ // @Override public void swapBodyItem(BodyLoc bodyLoc, boolean merc) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "swapBodyItem " + bodyLoc + "," + (merc ? "merc" : "player")); // #bodyToCursor(BodyLoc,boolean) Item newCursorItem; int newCursor; if (merc) { int i = mercData.itemData.unequip(bodyLoc); newCursor = itemData.add(newCursorItem = mercData.itemData.remove(i)); } else { newCursor = itemData.unequip(bodyLoc); newCursorItem = itemData.getItem(newCursor); } // #cursorToBody(BodyLoc,boolean) if (merc) { Item item = itemData.getItem(itemData.cursor); itemData.remove(itemData.cursor); mercData.itemData.equip(bodyLoc, item); if (newCursor >= itemData.cursor) newCursor--; // removing item invalidated the index } else { itemData.equip(bodyLoc, itemData.cursor); } itemData.cursor = newCursor; itemData.setLocation(newCursorItem, Location.CURSOR); } // @Override public void beltToCursor(int i) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "beltToCursor"); itemToCursor(i); } // @Override public void cursorToBelt(int x, int y) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "cursorToBelt"); assert itemData.cursor != ItemData.INVALID_ITEM; int i = itemData.cursor; itemData.cursor = ItemData.INVALID_ITEM; Item item = itemData.getItem(i); item.gridX = (byte) x; item.gridY = (byte) y; itemData.setLocation(item, Location.BELT); } /** * FIXME: originally worked as an aggregate call on {@link #cursorToBelt(int, int)} and * {@link #beltToCursor(int)}, and while that worked fine programically to pass the * assertions within {@link ItemData}, {@link ItemData.LocationListener#onChanged} * was being called out of order for setting the cursor, causing the cursor to be unset * within the UI immediately after being changed. */ // @Override public void swapBeltItem(int i) { if (DEBUG_ITEMS) Gdx.app.log(TAG, "swapBeltItem"); // #beltToCursor(int) Item newCursorItem = itemData.getItem(i); // #cursorToBelt(int,int) Item item = itemData.getItem(itemData.cursor); item.gridX = newCursorItem.gridX; item.gridY = newCursorItem.gridY; itemData.setLocation(item, Location.BELT); itemData.cursor = ItemData.INVALID_ITEM; itemData.pickup(i); } public static class MercData { public int flags; public int seed; public short name; public short type; public long xp; final Attributes statData = Attributes.obtainLarge(); final ItemData itemData = new ItemData(statData, null); public Attributes getStats() { return statData; } public ItemData getItems() { return itemData; } public String getName() { return String.format("0x%04X", name); } } public void clearListeners() { itemData.equipListeners.clear(); mercData.itemData.equipListeners.clear(); itemData.alternateListeners.clear(); mercData.itemData.alternateListeners.clear(); skillListeners.clear(); } public boolean addSkillListener(SkillListener l) { skillListeners.add(l); return true; } private void notifySkillChanged(IntIntMap skills, Array<StatRef> chargedSkills) { for (SkillListener l : skillListeners) l.onChanged(this, skills, chargedSkills); } public interface SkillListener { void onChanged(CharData client, IntIntMap skills, Array<StatRef> chargedSkills); } }
0
0.885174
1
0.885174
game-dev
MEDIA
0.806311
game-dev
0.916958
1
0.916958
OSGeo/grass
1,337
raster/r.watershed/seg/sseg_open.c
#include <grass/gis.h> #include <unistd.h> #include <fcntl.h> #include <grass/segment.h> #include <grass/glocale.h> #include "Gwater.h" int seg_open(SSEG *sseg, GW_LARGE_INT rows, GW_LARGE_INT cols, int row_in_seg, int col_in_seg, int nsegs_in_memory, int size_struct) { char *filename; int errflag; sseg->filename = NULL; sseg->fd = -1; filename = G_tempfile(); if (0 > (errflag = Segment_open(&(sseg->seg), filename, rows, cols, row_in_seg, col_in_seg, size_struct, nsegs_in_memory))) { if (errflag == -1) { G_warning(_("File name is invalid")); return -1; } else if (errflag == -2) { G_warning(_("File write error")); return -2; } else if (errflag == -3) { G_warning(_("Illegal parameters are passed")); return -3; } else if (errflag == -4) { G_warning(_("File could not be re-opened")); return -4; } else if (errflag == -5) { G_warning(_("Prepared file could not be read")); return -5; } else if (errflag == -6) { G_warning(_("Out of memory")); return -6; } } sseg->filename = filename; return 0; }
0
0.887084
1
0.887084
game-dev
MEDIA
0.406938
game-dev
0.929714
1
0.929714
Mortalknight/GW2_UI
18,957
settings/panels/panel_player.lua
local _, GW = ... local L = GW.L local StrUpper = GW.StrUpper local function LoadPlayerPanel(sWindow) local p = CreateFrame("Frame", nil, sWindow, "GwSettingsPanelTmpl") local p_player = CreateFrame("Frame", nil, p, "GwSettingsPanelTmpl") p_player.panelId = "player_general" p_player.header:SetFont(DAMAGE_TEXT_FONT, 20) p_player.header:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) p_player.header:SetText(PLAYER) p_player.sub:SetFont(UNIT_NAME_FONT, 12) p_player.sub:SetTextColor(181 / 255, 160 / 255, 128 / 255) p_player.sub:SetText(L["Modify the player frame settings."]) p_player.header:SetWidth(p_player.header:GetStringWidth()) p_player.breadcrumb:SetFont(DAMAGE_TEXT_FONT, 12) p_player.breadcrumb:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) p_player.breadcrumb:SetText(GENERAL) local p_player_aura = CreateFrame("Frame", nil, p, "GwSettingsPanelTmpl") p_player_aura.panelId = "player_aura" p_player_aura.header:SetFont(DAMAGE_TEXT_FONT, 20) p_player_aura.header:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) p_player_aura.header:SetText(PLAYER) p_player_aura.header:SetWidth(p_player_aura.header:GetStringWidth()) p_player_aura.breadcrumb:SetFont(DAMAGE_TEXT_FONT, 12) p_player_aura.breadcrumb:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) p_player_aura.breadcrumb:SetText(L["Buffs"]) p_player_aura.sub:SetFont(UNIT_NAME_FONT, 12) p_player_aura.sub:SetTextColor(181 / 255, 160 / 255, 128 / 255) p_player_aura.sub:SetText("") local p_player_debuff = CreateFrame("Frame", nil, p, "GwSettingsPanelTmpl") p_player_debuff.panelId = "player_debuff" p_player_debuff.header:SetFont(DAMAGE_TEXT_FONT, 20) p_player_debuff.header:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) p_player_debuff.header:SetText(PLAYER) p_player_debuff.sub:SetFont(UNIT_NAME_FONT, 12) p_player_debuff.sub:SetTextColor(181 / 255, 160 / 255, 128 / 255) p_player_debuff.sub:SetText("") p_player_debuff.header:SetWidth(p_player_debuff.header:GetStringWidth()) p_player_debuff.breadcrumb:SetFont(DAMAGE_TEXT_FONT, 12) p_player_debuff.breadcrumb:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) p_player_debuff.breadcrumb:SetText(L["Debuffs"]) local fader = CreateFrame("Frame", nil, p, "GwSettingsPanelTmpl") fader.panelId = "player_fader" fader.header:SetFont(DAMAGE_TEXT_FONT, 20) fader.header:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) fader.header:SetText(PLAYER) fader.sub:SetFont(UNIT_NAME_FONT, 12) fader.sub:SetTextColor(181 / 255, 160 / 255, 128 / 255) fader.sub:SetText("") fader.header:SetWidth(fader.header:GetStringWidth()) fader.breadcrumb:SetFont(DAMAGE_TEXT_FONT, 12) fader.breadcrumb:SetTextColor(GW.TextColors.LIGHT_HEADER.r,GW.TextColors.LIGHT_HEADER.g,GW.TextColors.LIGHT_HEADER.b) fader.breadcrumb:SetText(L["Fader"]) p_player:AddOption(L["Player frame in target frame style"], nil, {getterSetter = "PLAYER_AS_TARGET_FRAME", callback = function() GW.ShowRlPopup = true end, dependence = {["HEALTHGLOBE_ENABLED"] = true}}) p_player:AddOption(L["Show alternative background texture"], nil, {getterSetter = "PLAYER_AS_TARGET_FRAME_ALT_BACKGROUND", callback = function() if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}}) p_player:AddOption(L["Show absorb bar"], nil, {getterSetter = "PLAYER_SHOW_ABSORB_BAR", callback = function() if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}, hidden = GW.Classic}) p_player:AddOption(L["Extend Ressourcebar size"], nil, {getterSetter = "PlayerTargetFrameExtendRessourcebar", callback = function() if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}}) p_player:AddOption(RAID_USE_CLASS_COLORS, nil, {getterSetter = "player_CLASS_COLOR", callback = function() if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}}) p_player:AddOption(L["Show an additional resource bar"], nil, {getterSetter = "PLAYER_AS_TARGET_FRAME_SHOW_RESSOURCEBAR", callback = function() GwPlayerPowerBar:ToggleBar(); GW.UpdateClassPowerExtraManabar() end, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true, ["POWERBAR_ENABLED"] = true}}) p_player:AddOption(L["PvP Indicator"], nil, {getterSetter = "PLAYER_SHOW_PVP_INDICATOR", dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player:AddOption(L["Energy/Mana Ticker"], L["5 second rule: display remaining time"], {getterSetter = "PLAYER_ENERGY_MANA_TICK", PLAYER_ENERGY_MANA_TICK_HIDE_OFC = GW.Update5SrHot, dependence = {["POWERBAR_ENABLED"] = true}, hidden = GW.Retail}) p_player:AddOption(L["Show Energy/Mana Ticker only in combat"], nil, {getterSetter = "PLAYER_ENERGY_MANA_TICK", callback = GW.Update5SrHot, dependence = {["POWERBAR_ENABLED"] = true, ["PLAYER_ENERGY_MANA_TICK"] = true}, hidden = GW.Retail}) p_player:AddOption(L["Show spell queue window on castingbar"], nil, {getterSetter = "PLAYER_CASTBAR_SHOW_SPELL_QUEUEWINDOW", dependence = {["CASTINGBAR_ENABLED"] = true, ["CASTINGBAR_DATA"] = true}}) p_player:AddOption(L["Show character item info"], L["Display gems and enchants on the GW2 character panel"], {getterSetter = "SHOW_CHARACTER_ITEM_INFO", callback = function() if not GW.Classic then GW.ToggleCharacterItemInfo() end end, dependence = {["USE_CHARACTER_WINDOW"] = true}}) p_player:AddOption(L["Hide Blizzard dragon riding vigor"], nil, {getterSetter = "HIDE_BLIZZARD_VIGOR_BAR", dependence = {["HEALTHGLOBE_ENABLED"] = true}, hidden = not GW.Retail}) p_player:AddOption(L["Show classpower bar only in combat"], nil, {getterSetter = "CLASSPOWER_ONLY_SHOW_IN_COMBAT", callback = function() GW.UpdateClassPowerVisibilitySetting(GwPlayerClassPower, true) end, dependence = {["CLASS_POWER"] = true}, hidden = GW.Classic}) p_player:AddOption(L["Shorten health values"], nil, {getterSetter = "PLAYER_UNIT_HEALTH_SHORT_VALUES", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end; if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true}, hidden = GW.Classic}) p_player:AddOption(L["Shorten shield values"], nil, {getterSetter = "PLAYER_UNIT_SHIELD_SHORT_VALUES", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end; if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true}, hidden = GW.Classic}) p_player:AddOption(L["Advanced Casting Bar"], L["Enable or disable the advanced casting bar."], {getterSetter = "CASTINGBAR_DATA", callback = function(value) GW.TogglePlayerEnhancedCastbar(GwCastingBarPlayer, value); GW.TogglePlayerEnhancedCastbar(GwCastingBarPet, value); end, dependence = {["CASTINGBAR_ENABLED"] = true}}) p_player:AddOption(L["Ticks"], L["Display tick marks on the castbar for channelled spells. This will adjust automatically for spells like Drain Soul and add additional ticks based on haste."], {getterSetter = "showPlayerCastBarTicks", dependence = {["CASTINGBAR_ENABLED"] = true}}) p_player:AddOptionDropdown(COMPACT_UNIT_FRAME_PROFILE_HEALTHTEXT, nil, { getterSetter = "PLAYER_UNIT_HEALTH", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end; if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, optionsList = {"NONE", "PREC", "VALUE", "BOTH"}, optionNames = {NONE, STATUS_TEXT_PERCENT, STATUS_TEXT_VALUE, STATUS_TEXT_BOTH}, dependence = {["HEALTHGLOBE_ENABLED"] = true}}) p_player:AddOptionDropdown(L["Show Shield Value"], nil, { getterSetter = "PLAYER_UNIT_ABSORB", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end; if GwPlayerUnitFrame then GwPlayerUnitFrame:ToggleSettings() end end, optionsList = {"NONE", "PREC", "VALUE", "BOTH"}, optionNames = {NONE, STATUS_TEXT_PERCENT, STATUS_TEXT_VALUE, STATUS_TEXT_BOTH}, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = false}, hidde = GW.Classic}) p_player:AddOptionText(L["Dodge Bar Ability"], L["Enter the spell ID which should be tracked by the dodge bar.\nIf no ID is entered, the default abilities based on your specialization and talents are tracked."], { getterSetter = "PLAYER_TRACKED_DODGEBAR_SPELL", callback = function(self) local spellId = self:GetNumber() local name = "" if spellId > 0 and GW.IsSpellKnown(spellId) then local spellInfo = C_Spell.GetSpellInfo(spellId) name = spellInfo.name end self:SetText(name) GW.private.PLAYER_TRACKED_DODGEBAR_SPELL = name GW.private.PLAYER_TRACKED_DODGEBAR_SPELL_ID = spellId if GwDodgeBar then GwDodgeBar:InitBar() GwDodgeBar:SetupBar() end end, dependence = {["HEALTHGLOBE_ENABLED"] = true}, isPrivateSetting = true}) -- BUFF p_player_aura:AddOptionDropdown(L["Player Buff Growth Direction"], nil, { getterSetter = "PlayerBuffs.GrowDirection", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, optionsList = {"UP", "DOWN", "UPR", "DOWNR"}, optionNames = {StrUpper(L["Up"], 1, 1), StrUpper(L["Down"], 1, 1), L["Up and right"], L["Down and right"]}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionDropdown(L["Sort Method"], L["Defines how the group is sorted."], { getterSetter = "PlayerBuffs.SortMethod", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, optionsList = {"INDEX", "TIME", "NAME"}, optionNames = {L["Index"], L["Time"], NAME}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionDropdown(L["Sort Direction"], L["Defines the sort order of the selected sort method."], { getterSetter = "PlayerBuffs.SortDir", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, optionsList = {"+", "-"}, optionNames = {L["Ascending"], L["Descending"]}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionDropdown(L["Seperate"], L["Indicate whether buffs you cast yourself should be separated before or after."], { getterSetter = "PlayerBuffs.Seperate", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, optionsList = {-1, 0, 1}, optionNames = {L["Other's First"], L["No Sorting"], L["Your Auras First"]}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionSlider(L["Auras per row"], nil, { getterSetter = "PlayerBuffs.WrapAfter", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, min = 1, max = 20, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionSlider(L["Horizontal Spacing"], nil, { getterSetter = "PlayerBuffs.HorizontalSpacing", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, min = -20, max = 50, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionSlider(L["Vertical Spacing"], nil, { getterSetter = "PlayerBuffs.VerticalSpacing", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, min = 0, max = 50, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionSlider(L["Max Wraps"], nil, { getterSetter = "PlayerBuffs.MaxWraps", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, min = 1, max = 32, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionSlider(L["Size"], nil, { getterSetter = "PlayerBuffs.IconSize", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, min = 10, max = 80, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOptionSlider(L["Height"], nil, { getterSetter = "PlayerBuffs.IconHeight", callback = function() GW.UpdateAuraHeader(GW2UIPlayerBuffs) end, min = 10, max = 80, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true, ["PlayerBuffs.KeepSizeRatio"] = false}}) p_player_aura:AddOption(L["Keep Size Ratio"], nil, {getterSetter = "PlayerBuffs.KeepSizeRatio", callback = function(value) local widget = GW.FindSettingsWidgetByOption("PlayerBuffs.IconSize"); widget.title:SetText(value == true and L["Size"] or L["Width"]); GW.UpdateAuraHeader(GW2UIPlayerBuffs) end,dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_aura:AddOption(ANIMATION, L["Shows an animation for new de/buffs"], {getterSetter = "PlayerBuffs.NewAuraAnimation", dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) -- DEBUFF p_player_debuff:AddOptionDropdown(L["Player Debuffs Growth Direction"], nil, { getterSetter = "PlayerDebuffs.GrowDirection", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs, "PlayerDebuffFrame") end, optionsList = {"UP", "DOWN", "UPR", "DOWNR"}, optionNames = {StrUpper(L["Up"], 1, 1), StrUpper(L["Down"], 1, 1), L["Up and right"], L["Down and right"]}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionDropdown(L["Sort Method"], L["Defines how the group is sorted."], { getterSetter = "PlayerDebuffs.SortMethod", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, optionsList = {"INDEX", "TIME", "NAME"}, optionNames = {L["Index"], L["Time"], NAME}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionDropdown(L["Sort Direction"], L["Defines the sort order of the selected sort method."], { getterSetter = "PlayerDebuffs.SortDir", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, optionsList = {"+", "-"}, optionNames = {L["Ascending"], L["Descending"]}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionDropdown(L["Seperate"], L["Indicate whether buffs you cast yourself should be separated before or after."], { getterSetter = "PlayerDebuffs.Seperate", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, optionsList = {-1, 0, 1}, optionNames = {L["Other's First"], L["No Sorting"], L["Your Auras First"]}, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionSlider(L["Auras per row"], nil, { getterSetter = "PlayerDebuffs.WrapAfter", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, min = 1, max = 20, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionSlider(L["Horizontal Spacing"], nil, { getterSetter = "PlayerDebuffs.HorizontalSpacing", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, min = -20, max = 50, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionSlider(L["Vertical Spacing"], nil, { getterSetter = "PlayerDebuffs.VerticalSpacing", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, min = 0, max = 50, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionSlider(L["Max Wraps"], nil, { getterSetter = "PlayerDebuffs.MaxWraps", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, min = 1, max = 32, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionSlider(L["Size"], nil, { getterSetter = "PlayerDebuffs.IconSize", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, min = 10, max = 80, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOptionSlider(L["Height"], nil, { getterSetter = "PlayerDebuffs.IconHeight", callback = function() GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, min = 10, max = 80, decimalNumbers = 0, step = 1, dependence = {["PLAYER_BUFFS_ENABLED"] = true, ["PlayerDebuffs.KeepSizeRatio"] = false}}) p_player_debuff:AddOption(L["Keep Size Ratio"], nil, {getterSetter = "PlayerDebuffs.KeepSizeRatio", callback = function(value) local widget = GW.FindSettingsWidgetByOption("PlayerDebuffs.IconSize"); widget.title:SetText(value == true and L["Size"] or L["Width"]); GW.UpdateAuraHeader(GW2UIPlayerDebuffs) end, dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) p_player_debuff:AddOption(ANIMATION, L["Shows an animation for new de/buffs"], {getterSetter = "PlayerDebuffs.NewAuraAnimation", dependence = {["PLAYER_BUFFS_ENABLED"] = true}}) -- FADER fader:AddGroupHeader(L["Fader"]) fader:AddOptionDropdown(GW.NewSign .. L["Fader"], nil, { getterSetter = "playerFrameFader", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end end, optionsList = {"casting", "combat", "hover", "dynamicflight", "vehicle", "playertarget"}, optionNames = {L["Casting"], COMBAT, L["Hover"], DYNAMIC_FLIGHT, L["Vehicle"], TARGET}, dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}, checkbox = true, groupHeaderName = L["Fader"]}) fader:AddOptionSlider(GW.NewSign .. L["Smooth"], nil, { getterSetter = "playerFrameFader.smooth", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end end, min = 0, max = 3, decimalNumbers = 2, step = 0.01, groupHeaderName = L["Fader"], dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}}) fader:AddOptionSlider(GW.NewSign .. L["Min Alpha"], nil, { getterSetter = "playerFrameFader.minAlpha", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end end, min = 0, max = 1, decimalNumbers = 2, step = 0.01, groupHeaderName = L["Fader"], dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}}) fader:AddOptionSlider(GW.NewSign .. L["Max Alpha"], nil, { getterSetter = "playerFrameFader.maxAlpha", callback = function() if GW2_PlayerFrame then GW2_PlayerFrame:ToggleSettings() end end, min = 0, max = 1, decimalNumbers = 2, step = 0.01, groupHeaderName = L["Fader"], dependence = {["HEALTHGLOBE_ENABLED"] = true, ["PLAYER_AS_TARGET_FRAME"] = true}}) sWindow:AddSettingsPanel(p, PLAYER, L["Modify the player frame settings."], {{name = GENERAL, frame = p_player}, {name = L["Buffs"], frame = p_player_aura}, {name = L["Debuffs"], frame = p_player_debuff}, {name = L["Fader"], frame = fader}}) end GW.LoadPlayerPanel = LoadPlayerPanel
0
0.898556
1
0.898556
game-dev
MEDIA
0.842348
game-dev
0.974232
1
0.974232
daleao/sdv
1,734
Professions/Commands/StartTreasureHuntCommand.cs
namespace DaLion.Professions.Commands; #region using directives using DaLion.Shared.Attributes; using DaLion.Shared.Commands; #endregion using directives /// <summary>Initializes a new instance of the <see cref="StartTreasureHuntCommand"/> class.</summary> /// <param name="handler">The <see cref="CommandHandler"/> instance that handles this command.</param> [UsedImplicitly] [Debug] internal sealed class StartTreasureHuntCommand(CommandHandler handler) : ConsoleCommand(handler) { /// <inheritdoc /> public override string[] Triggers { get; } = ["hunt", "start"]; /// <inheritdoc /> public override string Documentation => "Triggers a hunt of the specified type at the current location."; /// <inheritdoc /> public override bool CallbackImpl(string trigger, string[] args) { if (args.Length < 1) { Log.W("You must specify the type of treasure hunt. Either 'Scavenger' or 'Prospector' key and value."); return false; } if (args[0].ToLowerInvariant() == "scavenger") { if (State.ScavengerHunt is null) { Log.W("The Scavenger Hunt instance has not been created."); return false; } State.ScavengerHunt.TryStart(Game1.currentLocation); return true; } if (args[0].ToLowerInvariant() == "prospector") { if (State.ProspectorHunt is null) { Log.W("The Prospector Hunt instance has not been created."); return false; } State.ProspectorHunt.TryStart(Game1.currentLocation); return true; } return true; } }
0
0.97619
1
0.97619
game-dev
MEDIA
0.967542
game-dev
0.938192
1
0.938192
pgf-tikz/pgf
3,056
tex/generic/pgf/graphdrawing/lua/pgf/gd/force/jedi/forcetypes/ForcePullToPoint.lua
-- Copyright 2014 by Ida Bruhns -- -- This file may be distributed and/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information --- This is a subclass of ForceTemplate, which is used to implement forces -- that work on individual vertices and pulls them to a specific point on the -- canvas. This point is given by the |desired at| option. The forces depend -- on the canvas position of the vertices relative to the canvas point it is -- pulled to. -- Imports local ForceTemplate = require "pgf.gd.force.jedi.base.ForceTemplate" local lib = require "pgf.gd.lib" local Preprocessing = require "pgf.gd.force.jedi.base.Preprocessing" -- Localize math functions local max = math.max local sqrt = math.sqrt local min = math.min -- Implementation starts here: local ForcePullToPoint = lib.class { base_class = ForceTemplate } function ForcePullToPoint:constructor () ForceTemplate.constructor(self) self.p = {} end -- This force class works on individual vertices and depends on their -- current position as well as the point it is desired at. Thus all vertices -- where the |desired at| option is set are added to the table |p| together -- with the point where they are wanted. -- -- @param v The vertices of the graph we are trying to find a layout for. function ForcePullToPoint:preprocess(v) for _,vertex in ipairs(v) do if vertex.options then local da = vertex.options["desired at"] if da then self.p[vertex]= {da} end end end end -- Applying the force to the vertices and adding the effect to the passed net -- force array -- -- @param data The parameters needed to apply the force: The options table, -- the current time stamp, an array containing the summed up net -- forces function ForcePullToPoint:applyTo(data) -- locals for speed local cap = self.force.cap local net_forces = data.net_forces local t_max = self.options["maximum time"] local t_now = data.t_now local p = self.p local time_fun = self.force.time_fun -- Evaluate time function local time_factor = time_fun(t_max, t_now) if time_factor == 0 then return end for v, point in pairs(p) do -- dereference local p1 = v.pos local p2 = point[1] -- calculate distance between vertex and centroid local x = p1.x - p2.x local y = p1.y - p2.y local d = max(sqrt(x*x+y*y),0.1) -- Include time function local h = d * time_factor -- scale effect according to direction local f = x * h local g = y * h -- cap effect if necessary if cap then if f <= 0 then x = max(-cap, f) else x = min(cap, f) end if g <= 0 then y = max(-cap, g) else y = min(cap, g) end else x = f y = g end -- add calculated effect to net forces local c1 = net_forces[v] c1.x = c1.x - x c1.y = c1.y - y end end return ForcePullToPoint
0
0.876929
1
0.876929
game-dev
MEDIA
0.566125
game-dev,graphics-rendering
0.950906
1
0.950906
folium-app/Cytrus
7,227
Core/include/core/hle/service/boss/online_service.h
// Copyright 2023 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #pragma once #include <string> #include <variant> #include <vector> #include "common/common_types.h" #include "core/hle/result.h" #include "core/loader/loader.h" namespace Kernel { class MappedBuffer; } namespace FileSys { class ArchiveBackend; struct Entry; class Path; } // namespace FileSys namespace Service::BOSS { constexpr u32 BOSS_PAYLOAD_HEADER_LENGTH = 0x28; constexpr u32 BOSS_MAGIC = Loader::MakeMagic('b', 'o', 's', 's'); constexpr u32 BOSS_PAYLOAD_MAGIC = 0x10001; constexpr u64 NEWS_PROG_ID = 0x0004013000003502; constexpr u32 BOSS_CONTENT_HEADER_LENGTH = 0x132; constexpr u32 BOSS_HEADER_WITH_HASH_LENGTH = 0x13C; constexpr u32 BOSS_ENTIRE_HEADER_LENGTH = BOSS_CONTENT_HEADER_LENGTH + BOSS_HEADER_WITH_HASH_LENGTH; constexpr u32 BOSS_EXTDATA_HEADER_LENGTH = 0x18; constexpr u32 BOSS_S_ENTRY_SIZE = 0xC00; constexpr u32 BOSS_SAVE_HEADER_SIZE = 4; constexpr std::size_t TASK_ID_SIZE = 8; constexpr std::size_t URL_SIZE = 0x200; constexpr std::size_t HEADERS_SIZE = 0x360; constexpr std::size_t CERTIDLIST_SIZE = 3; constexpr std::size_t TASKIDLIST_SIZE = 0x400; constexpr std::array<u8, 8> boss_system_savedata_id{ 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x01, 0x00, }; #pragma pack(push, 4) struct BossHeader { u8 header_length; std::array<u8, 11> zero1; u32_be unknown; u32_be download_date; std::array<u8, 4> zero2; u64_be program_id; std::array<u8, 4> zero3; u32_be datatype; u32_be payload_size; u32_be ns_data_id; u32_be version; }; #pragma pack(pop) static_assert(sizeof(BossHeader) == 0x34, "BossHeader has incorrect size"); struct NsDataEntry { std::string filename; BossHeader header; }; enum class NsDataHeaderInfoType : u8 { ProgramId = 0, Unknown = 1, Datatype = 2, PayloadSize = 3, NsDataId = 4, Version = 5, Everything = 6, }; struct NsDataHeaderInfo { u64 program_id; INSERT_PADDING_BYTES(4); u32 datatype; u32 payload_size; u32 ns_data_id; u32 version; INSERT_PADDING_BYTES(4); }; static_assert(sizeof(NsDataHeaderInfo) == 0x20, "NsDataHeaderInfo has incorrect size"); enum class PropertyID : u16 { Interval = 0x03, Duration = 0x04, Url = 0x07, Headers = 0x0D, CertId = 0x0E, CertIdList = 0x0F, LoadCert = 0x10, LoadRootCert = 0x11, TotalTasks = 0x35, TaskIdList = 0x36, }; struct BossSVData { INSERT_PADDING_BYTES(0x10); u64 program_id; std::array<char, TASK_ID_SIZE> task_id; }; struct BossSSData { INSERT_PADDING_BYTES(0x21C); std::array<u8, URL_SIZE> url; }; using BossTaskProperty = std::variant<u8, u16, u32, u64, std::vector<u8>, std::vector<u32>>; struct BossTaskProperties { bool task_result; std::map<PropertyID, BossTaskProperty> properties{ {static_cast<PropertyID>(0x00), u8()}, {static_cast<PropertyID>(0x01), u8()}, {static_cast<PropertyID>(0x02), u32()}, {PropertyID::Interval, u32()}, {PropertyID::Duration, u32()}, {static_cast<PropertyID>(0x05), u8()}, {static_cast<PropertyID>(0x06), u8()}, {PropertyID::Url, std::vector<u8>(URL_SIZE)}, {static_cast<PropertyID>(0x08), u32()}, {static_cast<PropertyID>(0x09), u8()}, {static_cast<PropertyID>(0x0A), std::vector<u8>(0x100)}, {static_cast<PropertyID>(0x0B), std::vector<u8>(0x200)}, {static_cast<PropertyID>(0x0C), u32()}, {PropertyID::Headers, std::vector<u8>(HEADERS_SIZE)}, {PropertyID::CertId, u32()}, {PropertyID::CertIdList, std::vector<u32>(CERTIDLIST_SIZE)}, {PropertyID::LoadCert, u8()}, {PropertyID::LoadRootCert, u8()}, {static_cast<PropertyID>(0x12), u8()}, {static_cast<PropertyID>(0x13), u32()}, {static_cast<PropertyID>(0x14), u32()}, {static_cast<PropertyID>(0x15), std::vector<u8>(0x40)}, {static_cast<PropertyID>(0x16), u32()}, {static_cast<PropertyID>(0x18), u8()}, {static_cast<PropertyID>(0x19), u8()}, {static_cast<PropertyID>(0x1A), u8()}, {static_cast<PropertyID>(0x1B), u32()}, {static_cast<PropertyID>(0x1C), u32()}, {static_cast<PropertyID>(0x1D), u8()}, {static_cast<PropertyID>(0x1E), u8()}, {static_cast<PropertyID>(0x1F), u8()}, {static_cast<PropertyID>(0x20), u8()}, {static_cast<PropertyID>(0x21), u8()}, {static_cast<PropertyID>(0x22), u8()}, {static_cast<PropertyID>(0x23), u32()}, {static_cast<PropertyID>(0x24), u8()}, {static_cast<PropertyID>(0x25), u32()}, {static_cast<PropertyID>(0x26), u32()}, {static_cast<PropertyID>(0x27), u32()}, {static_cast<PropertyID>(0x28), u64()}, {static_cast<PropertyID>(0x29), u64()}, {static_cast<PropertyID>(0x2A), u32()}, {static_cast<PropertyID>(0x2B), u32()}, {static_cast<PropertyID>(0x2C), u8()}, {static_cast<PropertyID>(0x2D), u16()}, {static_cast<PropertyID>(0x2E), u16()}, {static_cast<PropertyID>(0x2F), std::vector<u8>(0x40)}, {PropertyID::TotalTasks, u16()}, {PropertyID::TaskIdList, std::vector<u8>(TASKIDLIST_SIZE)}, {static_cast<PropertyID>(0x3B), u32()}, {static_cast<PropertyID>(0x3E), std::vector<u8>(0x200)}, {static_cast<PropertyID>(0x3F), u8()}, }; template <class Archive> void serialize(Archive& ar, const unsigned int); friend class boost::serialization::access; }; class OnlineService final { public: explicit OnlineService(u64 program_id_, u64 extdata_id_); Result InitializeSession(u64 init_program_id); void RegisterTask(const u32 size, Kernel::MappedBuffer& buffer); Result UnregisterTask(const u32 size, Kernel::MappedBuffer& buffer); void GetTaskIdList(); u16 GetNsDataIdList(const u32 filter, const u32 max_entries, Kernel::MappedBuffer& buffer); std::optional<NsDataEntry> GetNsDataEntryFromId(const u32 ns_data_id); Result GetNsDataHeaderInfo(const u32 ns_data_id, const NsDataHeaderInfoType type, const u32 size, Kernel::MappedBuffer& buffer); ResultVal<std::size_t> ReadNsData(const u32 ns_data_id, const u64 offset, const u32 size, Kernel::MappedBuffer& buffer); Result SendProperty(const u16 id, const u32 size, Kernel::MappedBuffer& buffer); Result ReceiveProperty(const u16 id, const u32 size, Kernel::MappedBuffer& buffer); private: std::unique_ptr<FileSys::ArchiveBackend> OpenBossExtData(); std::vector<FileSys::Entry> GetBossExtDataFiles(FileSys::ArchiveBackend* boss_archive); FileSys::Path GetBossDataDir(); std::vector<NsDataEntry> GetNsDataEntries(); BossTaskProperties current_props; std::map<std::string, BossTaskProperties> task_id_list; u64 program_id; u64 extdata_id; // For serialization explicit OnlineService() = default; template <class Archive> void serialize(Archive& ar, const unsigned int); friend class boost::serialization::access; }; } // namespace Service::BOSS
0
0.900497
1
0.900497
game-dev
MEDIA
0.365765
game-dev
0.624517
1
0.624517
JudsonSS/Jogos
5,877
Labs/Lab22/Inertia/Inertia/Engine.cpp
/********************************************************************************** // Engine (Cdigo Fonte) // // Criao: 15 Mai 2014 // Atualizao: 27 Set 2021 // Compilador: Visual C++ 2019 // // Descrio: A funo da Engine rodar jogos criados a partir da classe // abstrata Game. Todo jogo deve ser uma classe derivada de Game // e portanto deve implementar as funes membro Init, Update, Draw // e Finalize, que sero chamadas pelo motor em um lao de tempo real. // Para usar a classe Engine, o programador deve criar uma instncia // e chamar o mtodo Start(), passando um objeto derivado de Game. // **********************************************************************************/ #include "Engine.h" #include <windows.h> #include <sstream> using std::stringstream; // ------------------------------------------------------------------------------ // Inicializao de variveis estticas da classe Game * Engine::game = nullptr; // jogo em execuo Window * Engine::window = nullptr; // janela do jogo Graphics * Engine::graphics = nullptr; // dispositivo grfico Renderer * Engine::renderer = nullptr; // renderizador de sprites float Engine::frameTime = 0.0f; // tempo do quadro atual bool Engine::paused = false; // estado do game loop Timer Engine::timer; // medidor de tempo // ------------------------------------------------------------------------------- Engine::Engine() { // inicializa Component Object Model - COM (DirectX) if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) return; window = new Window(); graphics = new Graphics(); renderer = new Renderer(); } // ------------------------------------------------------------------------------- Engine::~Engine() { delete game; delete renderer; delete graphics; delete window; // libera Component Object Model (COM) CoUninitialize(); } // ----------------------------------------------------------------------------- int Engine::Start(Game* level) { game = level; // cria janela do jogo window->Create(); // inicializa dispositivo grfico graphics->Initialize(window); // inicializa renderizador de sprites renderer->Initialize(window, graphics); // ajusta a resoluo do Sleep para 1 milisegundo // requer uso da biblioteca winmm.lib timeBeginPeriod(1); int exitCode = Loop(); // volta a resoluo do Sleep ao valor original timeEndPeriod(1); return exitCode; } // ----------------------------------------------------------------------------- void Engine::Pause() { paused = true; timer.Stop(); } // ----------------------------------------------------------------------------- void Engine::Resume() { paused = false; timer.Start(); } // ------------------------------------------------------------------------------- int Engine::Loop() { // inicia contagem de tempo timer.Start(); // inicializao do jogo game->Init(); // mensagens do Windows MSG msg = { 0 }; // lao principal do jogo do { // testa se tem mensagem do windows para tratar if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { // ----------------------------------------------- // Pausa/Resume Jogo // ----------------------------------------------- if (window->KeyPress(VK_PAUSE)) { paused = !paused; if (paused) timer.Stop(); else timer.Start(); } // ----------------------------------------------- if (!paused) { // calcula o tempo do quadro frameTime = FrameTime(); // atualizao do jogo game->Update(); // limpa a tela para o prximo quadro graphics->Clear(); // desenha o jogo game->Draw(); // renderiza sprites renderer->Render(); // apresenta o jogo na tela (troca backbuffer/frontbuffer) graphics->Present(); } else { // tela de pausa game->OnPause(); } } } while (msg.message != WM_QUIT); // finalizao do jogo game->Finalize(); // encerra aplicao return int(msg.wParam); } // ----------------------------------------------------------------------------- float Engine::FrameTime() { #ifdef _DEBUG static float totalTime = 0.0f; // tempo total transcorrido static uint frameCount = 0; // contador de frames transcorridos #endif // tempo do frame atual em segundos frameTime = timer.Reset(); #ifdef _DEBUG // tempo acumulado dos frames totalTime += frameTime; // incrementa contador de frames frameCount++; // a cada 1000ms (1 segundo) atualiza indicador de FPS na janela if (totalTime >= 1.0f) { stringstream text; // fluxo de texto para mensagens text << std::fixed; // sempre mostra a parte fracionria text.precision(3); // trs casas depois da vrgula text << window->Title().c_str() << " " << "FPS: " << frameCount << " " << "Frame Time: " << frameTime * 1000 << " (ms)"; SetWindowText(window->Id(), text.str().c_str()); frameCount = 0; totalTime -= 1.0f; } #endif return frameTime; } // -----------------------------------------------------------------------------
0
0.660398
1
0.660398
game-dev
MEDIA
0.769903
game-dev,graphics-rendering
0.79711
1
0.79711
Space-Stories/space-station-14
2,813
Content.Client/Options/OptionsVisualizerSystem.cs
using Content.Shared.CCVar; using Robust.Client.GameObjects; using Robust.Shared.Configuration; using Robust.Shared.Reflection; namespace Content.Client.Options; /// <summary> /// Implements <see cref="OptionsVisualizerComponent"/>. /// </summary> public sealed class OptionsVisualizerSystem : EntitySystem { private static readonly (OptionVisualizerOptions, CVarDef<bool>)[] OptionVars = { (OptionVisualizerOptions.Test, CCVars.DebugOptionVisualizerTest), (OptionVisualizerOptions.ReducedMotion, CCVars.ReducedMotion), }; [Dependency] private readonly IConfigurationManager _cfg = default!; [Dependency] private readonly IReflectionManager _reflection = default!; private OptionVisualizerOptions _currentOptions; public override void Initialize() { base.Initialize(); foreach (var (_, cvar) in OptionVars) { Subs.CVar(_cfg, cvar, _ => CVarChanged()); } UpdateActiveOptions(); SubscribeLocalEvent<OptionsVisualizerComponent, ComponentStartup>(OnComponentStartup); } private void CVarChanged() { UpdateActiveOptions(); UpdateAllComponents(); } private void UpdateActiveOptions() { _currentOptions = OptionVisualizerOptions.Default; foreach (var (value, cVar) in OptionVars) { if (_cfg.GetCVar(cVar)) _currentOptions |= value; } } private void UpdateAllComponents() { var query = EntityQueryEnumerator<OptionsVisualizerComponent, SpriteComponent>(); while (query.MoveNext(out _, out var component, out var sprite)) { UpdateComponent(component, sprite); } } private void OnComponentStartup(EntityUid uid, OptionsVisualizerComponent component, ComponentStartup args) { if (!TryComp(uid, out SpriteComponent? sprite)) return; UpdateComponent(component, sprite); } private void UpdateComponent(OptionsVisualizerComponent component, SpriteComponent sprite) { foreach (var (layerKeyRaw, layerData) in component.Visuals) { object layerKey = _reflection.TryParseEnumReference(layerKeyRaw, out var @enum) ? @enum : layerKeyRaw; OptionsVisualizerComponent.LayerDatum? matchedDatum = null; foreach (var datum in layerData) { if ((datum.Options & _currentOptions) != datum.Options) continue; matchedDatum = datum; } if (matchedDatum == null) continue; var layerIndex = sprite.LayerMapReserveBlank(layerKey); sprite.LayerSetData(layerIndex, matchedDatum.Data); } } }
0
0.957765
1
0.957765
game-dev
MEDIA
0.721391
game-dev,graphics-rendering
0.976776
1
0.976776
PCGen/pcgen
3,545
PCGen-base/code/src/java/pcgen/base/graph/search/LoopDetectionAlgorithm.java
/* * Copyright 2020 (C) Tom Parker <thpr@users.sourceforge.net> * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA */ package pcgen.base.graph.search; import java.util.ArrayList; import java.util.List; import java.util.Objects; import pcgen.base.graph.base.DirectionalEdge; import pcgen.base.graph.base.Graph; /** * This is an implementation of a Loop Detector using a Depth First Search of a Graph. * * See http://en.wikipedia.org/wiki/Depth-first_search for a full definition. * * This traverse is a directional traverse. * * @param <N> * The format of the nodes in the Graph this LoopDetectionAlgorithm will * analyze */ public class LoopDetectionAlgorithm<N> { /** * Indicates the Graph on which this search algorithm is operating. */ private final Graph<N, ? extends DirectionalEdge<N>> graph; /** * A Set of the ancestor nodes which have already been visited by this search * algorithm. */ private final List<N> visitedNodes = new ArrayList<N>(); /** * Constructs a new LoopDetectionAlgorithm that will operate on the given Graph * * @param graph * The Graph this LoopDetectionAlgorithm will analyze */ public LoopDetectionAlgorithm(Graph<N, ? extends DirectionalEdge<N>> graph) { this.graph = Objects.requireNonNull(graph); } /** * Returns true if the Graph this LoopDetectionAlgorithm analyzes has a loop when * starting from the given node * * @param node * The node to start analysis from * @return true if the Graph this LoopDetectionAlgorithm analyzes has a loop when * starting from the given node; false otherwise */ public boolean hasLoopFromNode(N node) { if (visitedNodes.contains(Objects.requireNonNull(node))) { return true; } visitedNodes.add(node); for (DirectionalEdge<N> edge : graph.getAdjacentEdges(node)) { if (edge.isSource(node) && traverseFromEdge(edge)) { return true; } } visitedNodes.remove(node); return false; } /** * Traverses from the given Edge. * * @param edge * The edge to be traversed from * @return true if a loop was detected by a "child" node */ private boolean traverseFromEdge(DirectionalEdge<N> edge) { List<N> graphNodes = edge.getAdjacentNodes(); for (N node : graphNodes) { if (edge.isSink(node) && hasLoopFromNode(node)) { return true; } } return false; } /** * Returns a list of the looping nodes if a loop was detected by this * LoopDetectionAlgorithm. * * @return A list of the looping nodes if a loop was detected by this * LoopDetectionAlgorithm */ public List<N> getLoopingNodes() { return new ArrayList<N>(visitedNodes); } /** * Clears the visited node list so the LoopDetectionAlgorithm can be reused. */ public void clear() { visitedNodes.clear(); } }
0
0.822453
1
0.822453
game-dev
MEDIA
0.304505
game-dev
0.660671
1
0.660671
S2E/s2e
6,103
libs2eplugins/src/s2e/Plugins/OSMonitors/Windows/WindowsCrashMonitor.cpp
/// /// Copyright (C) 2016, Cyberhaven /// /// 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 <s2e/ConfigFile.h> #include <s2e/S2E.h> #include <s2e/S2EExecutor.h> #include <s2e/Utils.h> #include <iostream> #include <sstream> #include <s2e/Plugins/OSMonitors/Windows/BlueScreenInterceptor.h> #include <s2e/Plugins/OSMonitors/Windows/WindowsCrashDumpGenerator.h> #include <s2e/Plugins/OSMonitors/Windows/WindowsMonitor.h> #include "WindowsCrashMonitor.h" namespace s2e { namespace plugins { S2E_DEFINE_PLUGIN(WindowsCrashMonitor, "This plugin aggregates various sources of Windows crashes", "", "WindowsMonitor", "WindowsCrashDumpGenerator", "BlueScreenInterceptor"); void WindowsCrashMonitor::initialize() { m_windowsMonitor = s2e()->getPlugin<WindowsMonitor>(); m_bsodInterceptor = s2e()->getPlugin<BlueScreenInterceptor>(); m_bsodGenerator = s2e()->getPlugin<WindowsCrashDumpGenerator>(); auto cfg = s2e()->getConfig(); // Crash dumps may be heavy, disable them by default m_generateDumpOnKernelCrash = cfg->getBool(getConfigKey() + ".generateCrashDumpOnKernelCrash", false); m_generateDumpOnUserCrash = cfg->getBool(getConfigKey() + ".generateCrashDumpOnUserCrash", false); // Dumps may be vers large, compress them by default m_compressDumps = cfg->getBool(getConfigKey() + ".compressDumps", true); // Turn this off to let other plugins decide whether to kill the state or not // This option only applies to user-space crashes m_terminateOnCrash = cfg->getBool(getConfigKey() + ".terminateOnCrash", true); // Generate at most this many crash dumps m_maxCrashDumpCount = cfg->getInt(getConfigKey() + ".maxCrashDumps", 10); *m_crashCount.get() = 0; m_bsodInterceptor->onBlueScreen.connect(sigc::mem_fun(*this, &WindowsCrashMonitor::onBlueScreen)); } void WindowsCrashMonitor::generateCrashDump(S2EExecutionState *state, const vmi::windows::BugCheckDescription *info, bool isManual) { uint64_t *count = m_crashCount.acquire(); if (*count >= m_maxCrashDumpCount) { m_crashCount.release(); return; } ++*count; m_crashCount.release(); bool ret; std::string path = m_bsodGenerator->getPathForDump(state); if (isManual) { ret = m_bsodGenerator->generateManualDump(state, path, info); } else { ret = m_bsodGenerator->generateDump(state, path, info); } if (!ret) { return; } if (m_compressDumps) { compress_file(path); } } void WindowsCrashMonitor::onBlueScreen(S2EExecutionState *state, vmi::windows::BugCheckDescription *info) { if (m_generateDumpOnKernelCrash) { generateCrashDump(state, info, false); } onKernelModeCrash.emit(state, *info); // There is no point of letting the state up at this point, the guest is stuck with a BSOD s2e()->getExecutor()->terminateState(*state, "BSOD"); } /*****************************************************************/ void WindowsCrashMonitor::opUserModeCrash(S2EExecutionState *state, uint64_t guestDataPtr, const S2E_WINDOWS_CRASH_COMMAND &command) { WindowsUserModeCrash crash; crash.Pid = command.UserModeCrash.Pid; crash.ExceptionCode = command.UserModeCrash.ExceptionCode; crash.ExceptionAddress = command.UserModeCrash.ExceptionAddress; crash.ExceptionFlags = command.UserModeCrash.ExceptionFlags; bool ret = true; ret &= state->mem()->readString(command.UserModeCrash.ProgramName, crash.ProgramName); if (!ret) { getWarningsStream(state) << "could not read program name\n"; return; } if (m_generateDumpOnUserCrash) { crash.CrashDumpHeader.Buffer = command.Dump.Buffer; crash.CrashDumpHeader.Size = command.Dump.Size; onUserModeCrash.emit(state, crash); vmi::windows::BugCheckDescription info; info.guestHeader = crash.CrashDumpHeader.Buffer; info.headerSize = crash.CrashDumpHeader.Size; generateCrashDump(state, &info, true); } if (m_terminateOnCrash) { s2e()->getExecutor()->terminateState(*state, "User mode crash"); } } void WindowsCrashMonitor::handleOpcodeInvocation(S2EExecutionState *state, uint64_t guestDataPtr, uint64_t guestDataSize) { S2E_WINDOWS_CRASH_COMMAND command; if (guestDataSize != sizeof(command)) { getWarningsStream(state) << "mismatched S2E_WINDOWS_CRASH_COMMAND size\n"; return; } if (!state->mem()->read(guestDataPtr, &command, guestDataSize)) { getWarningsStream(state) << "could not read transmitted data\n"; return; } switch (command.Command) { case WINDOWS_USERMODE_CRASH: { opUserModeCrash(state, guestDataPtr, command); } break; default: { getWarningsStream(state) << "Unknown command\n"; } break; } } } // namespace plugins } // namespace s2e
0
0.882633
1
0.882633
game-dev
MEDIA
0.329736
game-dev
0.846637
1
0.846637
CalamityTeam/CalamityModPublic
89,087
NPCs/ExoMechs/Ares/AresBody.cs
using System; using System.Collections.Generic; using System.IO; using CalamityMod.Events; using CalamityMod.Graphics.Primitives; using CalamityMod.Items; using CalamityMod.Items.Accessories; using CalamityMod.Items.Armor.Vanity; using CalamityMod.Items.LoreItems; using CalamityMod.Items.Materials; using CalamityMod.Items.Mounts; using CalamityMod.Items.Placeables.Furniture.BossRelics; using CalamityMod.Items.Placeables.Furniture.DevPaintings; using CalamityMod.Items.Placeables.Furniture.Trophies; using CalamityMod.Items.Potions; using CalamityMod.Items.TreasureBags; using CalamityMod.Items.Weapons.DraedonsArsenal; using CalamityMod.Items.Weapons.Melee; using CalamityMod.Items.Weapons.Ranged; using CalamityMod.Items.Weapons.Rogue; using CalamityMod.Items.Weapons.Summon; using CalamityMod.NPCs.ExoMechs.Thanatos; using CalamityMod.Particles; using CalamityMod.Projectiles.Boss; using CalamityMod.Skies; using CalamityMod.Sounds; using CalamityMod.UI.VanillaBossBars; using CalamityMod.World; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; using ReLogic.Utilities; using Terraria; using Terraria.Audio; using Terraria.GameContent; using Terraria.GameContent.Bestiary; using Terraria.GameContent.ItemDropRules; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.NPCs.ExoMechs.Ares { [AutoloadBossHead] public class AresBody : ModNPC { // Used for loot public enum MechType { Ares = 0, Thanatos = 1, ArtemisAndApollo = 2 } public enum Phase { Normal = 0, Deathrays = 1 } public float AIState { get => NPC.Calamity().newAI[0]; set => NPC.Calamity().newAI[0] = value; } public enum SecondaryPhase { Nothing = 0, Passive = 1, PassiveAndImmune = 2 } public float SecondaryAIState { get => NPC.Calamity().newAI[1]; set => NPC.Calamity().newAI[1] = value; } public enum Enraged { No = 0, Yes = 1 } public float EnragedState { get => NPC.localAI[1]; set => NPC.localAI[1] = value; } public float VelocityBoostMult { get => NPC.localAI[2]; set => NPC.localAI[2] = value; } public ThanatosSmokeParticleSet SmokeDrawer = new ThanatosSmokeParticleSet(-1, 3, 0f, 16f, 1.5f); // This stores the sound slot of the deathray sound Ares makes, so it may be properly updated in terms of position and looped. public SlotId DeathraySoundSlot; // Spawn rate for enrage steam public const int ventCloudSpawnRate = 3; // Spawn rate for telegraph particles public const int telegraphParticlesSpawnRate = 5; // Number of frames on the X and Y axis private const int maxFramesX = 6; private const int maxFramesY = 8; // Counters for frames on the X and Y axis private int frameX = 0; private int frameY = 0; // Frame limit per animation, these are the specific frames where each animation ends private const int normalFrameLimit = 11; private const int firstStageDeathrayChargeFrameLimit = 23; private const int secondStageDeathrayChargeFrameLimit = 35; private const int finalStageDeathrayChargeFrameLimit = 47; // Default life ratio for the other mechs private const float defaultLifeRatio = 5f; // Variable used to stop the arm spawning loop private bool armsSpawned = false; // Exo Mechdusa stuff public bool exoMechdusa = false; public int neurontimer = 0; // Total duration of the deathray telegraph public const float deathrayTelegraphDuration_Normal = 150f; public const float deathrayTelegraphDuration_Expert = 120f; public const float deathrayTelegraphDuration_Rev = 105f; public const float deathrayTelegraphDuration_Death = 90f; public const float deathrayTelegraphDuration_BossRush = 60f; // Total duration of the deathrays public const float deathrayDuration = 600f; // Max distance from the target before they are unable to hear sound telegraphs private const float soundDistance = 4800f; // Distance the player has to be away from Ares in order to trigger the Deathray Spiral enrage private const float DeathrayEnrageDistance = 2480f; // Timers for the Tesla and Plasma Arms so that they fire at the proper times when they spawn and enter new phases public const float plasmaArmStartTimer = 260f; public const float teslaArmStartTimer = 80f; public static readonly SoundStyle EnragedSound = new("CalamityMod/Sounds/Custom/ExoMechs/AresEnraged"); public static readonly SoundStyle LaserStartSound = new("CalamityMod/Sounds/Custom/ExoMechs/AresCircleLaserStart"); public static readonly SoundStyle LaserLoopSound = new SoundStyle("CalamityMod/Sounds/Custom/ExoMechs/AresCircleLaserLoop") with { IsLooped = true }; public static readonly SoundStyle LaserEndSound = new("CalamityMod/Sounds/Custom/ExoMechs/AresCircleLaserEnd"); #region Textures public static Asset<Texture2D> GlowTexture; public static Asset<Texture2D> NeuronTexture; public static Asset<Texture2D> NeuronTexture_Glow; public static Asset<Texture2D> ArmTopTexture; public static Asset<Texture2D> ArmTopTexture2; public static Asset<Texture2D> ArmSegmentTexture; public static Asset<Texture2D> ArmTopShoulderTexture; public static Asset<Texture2D> ArmBottomConnectorTexture; public static Asset<Texture2D> ArmBottomTexture; public static Asset<Texture2D> ArmBottomTexture2; public static Asset<Texture2D> ArmBottomShoulderTexture; public static Asset<Texture2D> ArmTopTexture2_Glow; public static Asset<Texture2D> ArmSegmentTexture_Glow; public static Asset<Texture2D> ArmTopShoulderTexture_Glow; public static Asset<Texture2D> ArmBottomTexture_Glow; public static Asset<Texture2D> ArmBottomTexture2_Glow; public static Asset<Texture2D> ArmBottomShoulderTexture_Glow; #endregion public override void SetStaticDefaults() { NPCID.Sets.TrailingMode[NPC.type] = 3; NPCID.Sets.TrailCacheLength[NPC.type] = NPC.oldPos.Length; NPCID.Sets.BossBestiaryPriority.Add(Type); NPCID.Sets.NPCBestiaryDrawModifiers value = new NPCID.Sets.NPCBestiaryDrawModifiers() { PortraitScale = 0.54f, Scale = 0.4f }; NPCID.Sets.NPCBestiaryDrawOffset[Type] = value; if (!Main.dedServ) { string AresPath = "CalamityMod/NPCs/ExoMechs/Ares/Ares"; GlowTexture = ModContent.Request<Texture2D>(Texture + "Glow", AssetRequestMode.AsyncLoad); NeuronTexture = ModContent.Request<Texture2D>("CalamityMod/NPCs/ExoMechs/AergiaNeuron", AssetRequestMode.AsyncLoad); NeuronTexture_Glow = ModContent.Request<Texture2D>("CalamityMod/NPCs/ExoMechs/AergiaNeuron_Glow", AssetRequestMode.AsyncLoad); ArmTopTexture = ModContent.Request<Texture2D>(AresPath + "ArmTopPart1", AssetRequestMode.AsyncLoad); ArmTopTexture2 = ModContent.Request<Texture2D>(AresPath + "ArmTopPart2", AssetRequestMode.AsyncLoad); ArmSegmentTexture = ModContent.Request<Texture2D>(AresPath + "ArmTopSegment", AssetRequestMode.AsyncLoad); ArmTopShoulderTexture = ModContent.Request<Texture2D>(AresPath + "ArmTopShoulder", AssetRequestMode.AsyncLoad); ArmBottomConnectorTexture = ModContent.Request<Texture2D>(AresPath + "BottomArmConnector", AssetRequestMode.AsyncLoad); ArmBottomTexture = ModContent.Request<Texture2D>(AresPath + "BottomArmPart1", AssetRequestMode.AsyncLoad); ArmBottomTexture2 = ModContent.Request<Texture2D>(AresPath + "BottomArmPart2", AssetRequestMode.AsyncLoad); ArmBottomShoulderTexture = ModContent.Request<Texture2D>(AresPath + "BottomArmShoulder", AssetRequestMode.AsyncLoad); ArmTopTexture2_Glow = ModContent.Request<Texture2D>(AresPath + "ArmTopPart2Glow", AssetRequestMode.AsyncLoad); ArmSegmentTexture_Glow = ModContent.Request<Texture2D>(AresPath + "ArmTopSegmentGlow", AssetRequestMode.AsyncLoad); ArmTopShoulderTexture_Glow = ModContent.Request<Texture2D>(AresPath + "ArmTopShoulderGlow", AssetRequestMode.AsyncLoad); ArmBottomTexture_Glow = ModContent.Request<Texture2D>(AresPath + "BottomArmPart1Glow", AssetRequestMode.AsyncLoad); ArmBottomTexture2_Glow = ModContent.Request<Texture2D>(AresPath + "BottomArmPart2Glow", AssetRequestMode.AsyncLoad); ArmBottomShoulderTexture_Glow = ModContent.Request<Texture2D>(AresPath + "BottomArmShoulderGlow", AssetRequestMode.AsyncLoad); } } public override void SetDefaults() { NPC.npcSlots = 5f; NPC.damage = 100; NPC.width = 220; NPC.height = 252; NPC.defense = 100; NPC.DR_NERD(0.35f); NPC.LifeMaxNERB(1250000, 1495000, 650000); double HPBoost = CalamityConfig.Instance.BossHealthBoost * 0.01; NPC.lifeMax += (int)(NPC.lifeMax * HPBoost); NPC.aiStyle = -1; AIType = -1; NPC.Opacity = 0f; NPC.knockBackResist = 0f; NPC.value = Item.buyPrice(15, 0, 0, 0); NPC.noGravity = true; NPC.noTileCollide = true; NPC.DeathSound = CommonCalamitySounds.ExoDeathSound; NPC.netAlways = true; NPC.boss = true; NPC.BossBar = ModContent.GetInstance<ExoMechsBossBar>(); NPC.Calamity().VulnerableToSickness = false; NPC.Calamity().VulnerableToElectricity = true; } public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) { bestiaryEntry.Info.AddRange(new IBestiaryInfoElement[] { new FlavorTextBestiaryInfoElement("Mods.CalamityMod.Bestiary.Ares") }); } public override void BossHeadSlot(ref int index) { if (SecondaryAIState == (float)SecondaryPhase.PassiveAndImmune) index = -1; } public override void SendExtraAI(BinaryWriter writer) { writer.Write(frameX); writer.Write(frameY); writer.Write(armsSpawned); writer.Write(exoMechdusa); writer.Write(NPC.dontTakeDamage); writer.Write(NPC.localAI[0]); writer.Write(NPC.localAI[1]); writer.Write(NPC.localAI[2]); for (int i = 0; i < 4; i++) writer.Write(NPC.Calamity().newAI[i]); writer.Write(neurontimer); } public override void ReceiveExtraAI(BinaryReader reader) { frameX = reader.ReadInt32(); frameY = reader.ReadInt32(); armsSpawned = reader.ReadBoolean(); exoMechdusa = reader.ReadBoolean(); NPC.dontTakeDamage = reader.ReadBoolean(); NPC.localAI[0] = reader.ReadSingle(); NPC.localAI[1] = reader.ReadSingle(); NPC.localAI[2] = reader.ReadSingle(); for (int i = 0; i < 4; i++) NPC.Calamity().newAI[i] = reader.ReadSingle(); neurontimer = reader.ReadInt32(); } public override void AI() { CalamityGlobalNPC calamityGlobalNPC = NPC.Calamity(); CalamityGlobalNPC.draedonExoMechPrime = NPC.whoAmI; NPC.frame = new Rectangle(NPC.width * frameX, NPC.height * frameY, NPC.width, NPC.height); // Difficulty modes bool bossRush = BossRushEvent.BossRushActive; bool death = CalamityWorld.death || bossRush; bool revenge = CalamityWorld.revenge || bossRush; bool expertMode = Main.expertMode || bossRush; if (NPC.ai[2] > 0f) NPC.realLife = (int)NPC.ai[2]; // Spawn arms if (Main.netMode != NetmodeID.MultiplayerClient) { if (!armsSpawned && NPC.ai[0] == 0f) { int totalArms = 4; int Previous = NPC.whoAmI; for (int i = 0; i < totalArms; i++) { int lol = 0; switch (i) { case 0: lol = NPC.NewNPC(NPC.GetSource_FromAI(), (int)NPC.position.X + (NPC.width / 2), (int)NPC.position.Y + (NPC.height / 2), ModContent.NPCType<AresLaserCannon>(), NPC.whoAmI); break; case 1: lol = NPC.NewNPC(NPC.GetSource_FromAI(), (int)NPC.position.X + (NPC.width / 2), (int)NPC.position.Y + (NPC.height / 2), ModContent.NPCType<AresPlasmaFlamethrower>(), NPC.whoAmI); Main.npc[lol].Calamity().newAI[1] = plasmaArmStartTimer; break; case 2: lol = NPC.NewNPC(NPC.GetSource_FromAI(), (int)NPC.position.X + (NPC.width / 2), (int)NPC.position.Y + (NPC.height / 2), ModContent.NPCType<AresTeslaCannon>(), NPC.whoAmI); Main.npc[lol].Calamity().newAI[1] = teslaArmStartTimer; break; case 3: lol = NPC.NewNPC(NPC.GetSource_FromAI(), (int)NPC.position.X + (NPC.width / 2), (int)NPC.position.Y + (NPC.height / 2), ModContent.NPCType<AresGaussNuke>(), NPC.whoAmI); break; default: break; } Main.npc[lol].realLife = NPC.whoAmI; Main.npc[lol].ai[2] = NPC.whoAmI; Main.npc[lol].ai[1] = Previous; Main.npc[Previous].ai[0] = lol; NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, lol, 0f, 0f, 0f, 0); Previous = lol; } if (exoMechdusa) { NPC apolloNPC = CalamityUtils.SpawnBossBetter(NPC.Center, ModContent.NPCType<Apollo.Apollo>()); apolloNPC.ModNPC<Apollo.Apollo>().exoMechdusa = true; NPC artemisNPC = CalamityUtils.SpawnBossBetter(NPC.Center, ModContent.NPCType<Artemis.Artemis>()); artemisNPC.ModNPC<Artemis.Artemis>().exoMechdusa = true; NPC thanosNPC = CalamityUtils.SpawnBossBetter(NPC.Center, ModContent.NPCType<ThanatosHead>()); thanosNPC.ModNPC<ThanatosHead>().exoMechdusa = true; } armsSpawned = true; } } if (exoMechdusa) { int yoffset = 180; int xoffset = 180; Vector2 NeuronRight = new Vector2(NPC.Center.X + xoffset, NPC.Center.Y + yoffset); Vector2 NeuronLeft = new Vector2(NPC.Center.X - xoffset, NPC.Center.Y + yoffset); NPC.alpha = 0; NPC.dontTakeDamage = true; neurontimer++; if (Main.netMode != NetmodeID.MultiplayerClient) { if (neurontimer >= 180) { float variance = MathHelper.TwoPi / 6; for (int i = 0; i < 6; i++) { Vector2 velocity = new Vector2(0f, 6f); velocity = velocity.RotatedBy(variance * i); velocity.Normalize(); Vector2 betweenR = NeuronRight + velocity * 650; Vector2 betweenL = NeuronLeft + velocity * 650; Terraria.Audio.SoundEngine.PlaySound(CommonCalamitySounds.LaserCannonSound with { Volume = CommonCalamitySounds.LaserCannonSound.Volume - 0.2f, Pitch = CommonCalamitySounds.LaserCannonSound.Pitch + 0.2f }, NeuronRight); Projectile.NewProjectile(NPC.GetSource_FromAI(), betweenL, betweenL + velocity, ModContent.ProjectileType<ArtemisLaser>(), 111, 0f, Main.myPlayer, 7, NPC.whoAmI); Projectile.NewProjectile(NPC.GetSource_FromAI(), betweenR, betweenR + velocity, ModContent.ProjectileType<ArtemisLaser>(), 111, 0f, Main.myPlayer, 7, NPC.whoAmI); } neurontimer = 0; } } if (NPC.CountNPCS(ModContent.NPCType<Artemis.Artemis>()) > 0 || NPC.CountNPCS(ModContent.NPCType<ThanatosHead>()) > 0) { NPC.TargetClosest(); Vector2 where2 = new Vector2(Main.player[NPC.target].Center.X + 600, Main.player[NPC.target].Center.Y - 200); if (CalamityGlobalNPC.draedonExoMechWorm != -1) { if (Main.npc[CalamityGlobalNPC.draedonExoMechWorm].Calamity().newAI[0] == (float)ThanatosHead.Phase.Deathray) { where2 = new Vector2(Main.npc[CalamityGlobalNPC.draedonExoMechWorm].position.X, Main.npc[CalamityGlobalNPC.draedonExoMechWorm].position.Y - 40); NPC.position = where2; } else { CalamityUtils.SmoothMovement(NPC, 100, where2 - NPC.Center, 8, 1.4f, true); } } else if (CalamityGlobalNPC.draedonExoMechTwinGreen != -1) { if (Main.npc[CalamityGlobalNPC.draedonExoMechTwinRed].Calamity().newAI[0] == (float)Artemis.Artemis.Phase.Deathray) { where2 = new Vector2(Main.npc[CalamityGlobalNPC.draedonExoMechTwinRed].position.X, Main.npc[CalamityGlobalNPC.draedonExoMechTwinRed].position.Y); NPC.position = where2; } else if (Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].Calamity().newAI[0] == (float)Apollo.Apollo.Phase.ChargeCombo || Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].Calamity().newAI[0] == (float)Apollo.Apollo.Phase.LineUpChargeCombo) { where2 = new Vector2(Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].position.X, Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].position.Y); NPC.position = where2; } else { CalamityUtils.SmoothMovement(NPC, 100, where2 - NPC.Center, 8, 1.4f, true); } } else { CalamityUtils.SmoothMovement(NPC, 100, where2 - NPC.Center, 8, 1.4f, true); } return; } } if (NPC.life > Main.npc[(int)NPC.ai[0]].life) NPC.life = Main.npc[(int)NPC.ai[0]].life; // Percent life remaining float lifeRatio = NPC.life / (float)NPC.lifeMax; // Check if the other exo mechs are alive int otherExoMechsAlive = 0; bool exoWormAlive = false; bool exoTwinsAlive = false; if (CalamityGlobalNPC.draedonExoMechWorm != -1) { if (Main.npc[CalamityGlobalNPC.draedonExoMechWorm].active) { otherExoMechsAlive++; exoWormAlive = true; } } // There is no point in checking for the other twin because they have linked HP if (CalamityGlobalNPC.draedonExoMechTwinGreen != -1) { if (Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].active) { otherExoMechsAlive++; exoTwinsAlive = true; } } // These are 5 by default to avoid triggering passive phases after the other mechs are dead float exoWormLifeRatio = defaultLifeRatio; float exoTwinsLifeRatio = defaultLifeRatio; if (exoWormAlive) exoWormLifeRatio = Main.npc[CalamityGlobalNPC.draedonExoMechWorm].life / (float)Main.npc[CalamityGlobalNPC.draedonExoMechWorm].lifeMax; if (exoTwinsAlive) exoTwinsLifeRatio = Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].life / (float)Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].lifeMax; float totalOtherExoMechLifeRatio = exoWormLifeRatio + exoTwinsLifeRatio; // Check if any of the other mechs are passive bool exoWormPassive = false; bool exoTwinsPassive = false; if (exoWormAlive) exoWormPassive = Main.npc[CalamityGlobalNPC.draedonExoMechWorm].Calamity().newAI[1] == (float)ThanatosHead.SecondaryPhase.Passive; if (exoTwinsAlive) exoTwinsPassive = Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].Calamity().newAI[1] == (float)Apollo.Apollo.SecondaryPhase.Passive; bool anyOtherExoMechPassive = exoWormPassive || exoTwinsPassive; // Check if any of the other mechs were spawned first bool exoWormWasFirst = false; bool exoTwinsWereFirst = false; if (exoWormAlive) exoWormWasFirst = Main.npc[CalamityGlobalNPC.draedonExoMechWorm].ai[3] == 1f; if (exoTwinsAlive) exoTwinsWereFirst = Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].ai[3] == 1f; bool otherExoMechWasFirst = exoWormWasFirst || exoTwinsWereFirst; // Check for Draedon bool draedonAlive = false; if (CalamityGlobalNPC.draedon != -1) { if (Main.npc[CalamityGlobalNPC.draedon].active) draedonAlive = true; } // Prevent mechs from being respawned if (otherExoMechWasFirst) { if (NPC.ai[3] < 1f) NPC.ai[3] = 1f; } // Phases bool spawnOtherExoMechs = lifeRatio < 0.7f && NPC.ai[3] == 0f; bool berserk = lifeRatio < 0.4f || (otherExoMechsAlive == 0 && lifeRatio < 0.7f); bool lastMechAlive = berserk && otherExoMechsAlive == 0; // If Ares doesn't go berserk bool otherMechIsBerserk = exoWormLifeRatio < 0.4f || exoTwinsLifeRatio < 0.4f; // Whether Ares should be buffed while in berserk phase bool shouldGetBuffedByBerserkPhase = berserk && !otherMechIsBerserk; // Get a target if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) NPC.TargetClosest(); // Despawn safety, make sure to target another player if the current player target is too far away if (Vector2.Distance(Main.player[NPC.target].Center, NPC.Center) > CalamityGlobalNPC.CatchUpDistance200Tiles) NPC.TargetClosest(); // Target variable Player player = Main.player[NPC.target]; // General AI pattern // 0 - Fly above target // 1 - Fly towards the target, slow down when close enough // 2 - Fire deathrays from telegraph locations to avoid cheap hits and rotate them around for 10 seconds while the plasma and tesla arms fire projectiles to make dodging difficult // 3 - Go passive and fly above the target while firing less projectiles // 4 - Go passive, immune and invisible; fly above the target and do nothing until next phase // Attack patterns // If spawned first // Phase 1 - 0 // Phase 2 - 4 // Phase 3 - 3 // If berserk, this is the last phase of Ares // Phase 4 - 1, 2 // If not berserk // Phase 4 - 4 // Phase 5 - 0 // If berserk, this is the last phase of Ares // Phase 6 - 1, 2 // If not berserk // Phase 6 - 4 // Berserk, final phase of Ares // Phase 7 - 1, 2 // Rotation NPC.rotation = NPC.velocity.X * 0.003f; // Enrage check if (EnragedState == (float)Enraged.Yes) NPC.Calamity().CurrentlyEnraged = true; // Despawn if target is dead if (player.dead) { NPC.TargetClosest(false); player = Main.player[NPC.target]; if (player.dead) { AIState = (float)Phase.Normal; calamityGlobalNPC.newAI[2] = 0f; calamityGlobalNPC.newAI[3] = 0f; NPC.dontTakeDamage = true; NPC.velocity.Y -= 1f; if ((double)NPC.position.Y < Main.topWorld + 16f) NPC.velocity.Y -= 1f; if ((double)NPC.position.Y < Main.topWorld + 16f) { for (int a = 0; a < Main.maxNPCs; a++) { if (Main.npc[a].type == NPC.type || Main.npc[a].type == ModContent.NPCType<Artemis.Artemis>() || Main.npc[a].type == ModContent.NPCType<Apollo.Apollo>() || Main.npc[a].type == ModContent.NPCType<AresLaserCannon>() || Main.npc[a].type == ModContent.NPCType<AresPlasmaFlamethrower>() || Main.npc[a].type == ModContent.NPCType<AresTeslaCannon>() || Main.npc[a].type == ModContent.NPCType<AresGaussNuke>() || Main.npc[a].type == ModContent.NPCType<ThanatosHead>() || Main.npc[a].type == ModContent.NPCType<ThanatosBody1>() || Main.npc[a].type == ModContent.NPCType<ThanatosBody2>() || Main.npc[a].type == ModContent.NPCType<ThanatosTail>()) Main.npc[a].active = false; } } return; } } // Default vector to fly to Vector2 destination = SecondaryAIState == (float)SecondaryPhase.PassiveAndImmune ? new Vector2(player.Center.X, player.Center.Y - 800f) : AIState != (float)Phase.Deathrays ? new Vector2(player.Center.X, player.Center.Y - 425f) : player.Center; // Velocity and acceleration values float baseVelocityMult = (shouldGetBuffedByBerserkPhase ? 0.25f : 0f) + (bossRush ? 1.15f : death ? 1.1f : revenge ? 1.075f : expertMode ? 1.05f : 1f); float baseVelocity = (EnragedState == (float)Enraged.Yes ? 28f : 20f) * baseVelocityMult; float baseAcceleration = shouldGetBuffedByBerserkPhase ? 1.25f : 1f; float decelerationVelocityMult = 0.85f; // Distance where Ares stops moving float movementDistanceGateValue = 50f; // Scale up velocity over time if too far from destination Vector2 distanceFromDestination = destination - NPC.Center; if (distanceFromDestination.Length() > movementDistanceGateValue && AIState != (float)Phase.Deathrays) { if (VelocityBoostMult < 1f) VelocityBoostMult += 0.004f; } else { if (VelocityBoostMult > 0f) VelocityBoostMult -= 0.004f; } baseVelocity *= 1f + VelocityBoostMult; // Distance from target float distanceFromTarget = Vector2.Distance(NPC.Center, player.Center); // Gate values float deathrayPhaseGateValue = lastMechAlive ? 420f : 600f; float deathrayDistanceGateValue = 480f; // Enter deathray phase again more quickly if enraged if (EnragedState == (float)Enraged.Yes) deathrayPhaseGateValue *= 0.75f; // Emit steam while enraged SmokeDrawer.ParticleSpawnRate = 9999999; if (EnragedState == (float)Enraged.Yes) { SmokeDrawer.ParticleSpawnRate = ventCloudSpawnRate; SmokeDrawer.BaseMoveRotation = NPC.rotation + MathHelper.PiOver2; SmokeDrawer.SpawnAreaCompactness = 80f; // Increase DR during enrage NPC.Calamity().DR = 0.85f; } else NPC.Calamity().DR = 0.35f; calamityGlobalNPC.CurrentlyIncreasingDefenseOrDR = EnragedState == (float)Enraged.Yes; SmokeDrawer.Update(); // Passive and Immune phases switch ((int)SecondaryAIState) { case (int)SecondaryPhase.Nothing: // Spawn the other mechs if Ares is first and not Exo Mechdusa if (otherExoMechsAlive == 0 && !exoMechdusa) { if (spawnOtherExoMechs) { // Reset everything if (NPC.ai[3] < 1f) NPC.ai[3] = 1f; SecondaryAIState = (float)SecondaryPhase.PassiveAndImmune; NPC.TargetClosest(); // Draedon text for the start of phase 2 if (draedonAlive) { Main.npc[CalamityGlobalNPC.draedon].localAI[0] = 1f; Main.npc[CalamityGlobalNPC.draedon].ai[0] = Draedon.ExoMechPhaseDialogueTime; } if (Main.netMode != NetmodeID.MultiplayerClient) { // Spawn the fuckers NPC.SpawnOnPlayer(player.whoAmI, ModContent.NPCType<ThanatosHead>()); NPC.SpawnOnPlayer(player.whoAmI, ModContent.NPCType<Artemis.Artemis>()); NPC.SpawnOnPlayer(player.whoAmI, ModContent.NPCType<Apollo.Apollo>()); } } } else { // If not spawned first, go to passive state if any other mech is passive or if Ares is under 70% life // Do not run this if berserk // Do not run this if any exo mech is dead if ((anyOtherExoMechPassive || lifeRatio < 0.7f) && !berserk && totalOtherExoMechLifeRatio < 5f) { // Tells Ares to return to the battle in passive state and reset everything SecondaryAIState = (float)SecondaryPhase.Passive; NPC.TargetClosest(); } // Go passive and immune if one of the other mechs is berserk // This is only called if two exo mechs are alive in ideal scenarios // This is not called if Ares and another one or two mechs are berserk if (otherMechIsBerserk && !berserk) { // Reset everything if (NPC.ai[3] < 2f) NPC.ai[3] = 2f; SecondaryAIState = (float)SecondaryPhase.PassiveAndImmune; NPC.TargetClosest(); // Phase 6, when 1 mech goes berserk and the other one leaves if (draedonAlive) { Main.npc[CalamityGlobalNPC.draedon].localAI[0] = 5f; Main.npc[CalamityGlobalNPC.draedon].ai[0] = Draedon.ExoMechPhaseDialogueTime; } } } break; // Fire projectiles less often, this happens when all 3 mechs are present and attacking case (int)SecondaryPhase.Passive: // Enter passive and invincible phase if one of the other exo mechs is berserk if (otherMechIsBerserk) { // Reset everything if (NPC.ai[3] < 2f) NPC.ai[3] = 2f; SecondaryAIState = (float)SecondaryPhase.PassiveAndImmune; NPC.TargetClosest(); } // If Ares is the first mech to go berserk if (berserk) { // Reset everything NPC.TargetClosest(); // Never be passive if berserk SecondaryAIState = (float)SecondaryPhase.Nothing; // Phase 4, when 1 mech goes berserk and the other 2 leave if (exoWormAlive && exoTwinsAlive) { if (draedonAlive) { Main.npc[CalamityGlobalNPC.draedon].localAI[0] = 3f; Main.npc[CalamityGlobalNPC.draedon].ai[0] = Draedon.ExoMechPhaseDialogueTime; } } } break; // Fly above target and become immune case (int)SecondaryPhase.PassiveAndImmune: // Enter the fight again if any of the other exo mechs is below 70% and other mechs aren't berserk if ((exoWormLifeRatio < 0.7f || exoTwinsLifeRatio < 0.7f) && !otherMechIsBerserk) { // Tells Ares to return to the battle in passive state and reset everything // Return to normal phases if one or more mechs have been downed SecondaryAIState = totalOtherExoMechLifeRatio > 5f ? (float)SecondaryPhase.Nothing : (float)SecondaryPhase.Passive; NPC.TargetClosest(); // Phase 3, when all 3 mechs attack at the same time if (exoWormAlive && exoTwinsAlive) { if (draedonAlive) { Main.npc[CalamityGlobalNPC.draedon].localAI[0] = 2f; Main.npc[CalamityGlobalNPC.draedon].ai[0] = Draedon.ExoMechPhaseDialogueTime; } } } // This is here just in case if (berserk) { // Reset everything NPC.TargetClosest(); // Never be passive if berserk SecondaryAIState = (float)SecondaryPhase.Nothing; } break; } // Adjust opacity bool invisiblePhase = SecondaryAIState == (float)SecondaryPhase.PassiveAndImmune; NPC.dontTakeDamage = invisiblePhase; if (!invisiblePhase) { NPC.Opacity += 0.2f; if (NPC.Opacity > 1f) NPC.Opacity = 1f; } else { NPC.Opacity -= 0.05f; if (NPC.Opacity < 0f) NPC.Opacity = 0f; } // Attacking phases switch ((int)AIState) { // Fly above the target case (int)Phase.Normal: // Smooth movement towards the location Ares is meant to be at CalamityUtils.SmoothMovement(NPC, movementDistanceGateValue, distanceFromDestination, baseVelocity, 0f, false); if (shouldGetBuffedByBerserkPhase) { calamityGlobalNPC.newAI[2] += 1f; if (calamityGlobalNPC.newAI[2] > deathrayPhaseGateValue) { // Despawn stupid fucking dog shit to avoid screaming the word "cunt" for (int x = 0; x < Main.maxProjectiles; x++) { Projectile projectile = Main.projectile[x]; if (projectile.active) { if (projectile.type == ModContent.ProjectileType<AresTeslaOrb>() || projectile.type == ModContent.ProjectileType<AresPlasmaFireball>() || projectile.type == ModContent.ProjectileType<AresPlasmaBolt>() || projectile.type == ModContent.ProjectileType<AresGaussNukeProjectile>() || projectile.type == ModContent.ProjectileType<AresGaussNukeProjectileSpark>()) { if (projectile.timeLeft > 15) projectile.timeLeft = 15; if (projectile.type == ModContent.ProjectileType<AresPlasmaFireball>()) { projectile.ai[0] = -1f; projectile.ai[1] = -1f; } else if (projectile.type == ModContent.ProjectileType<AresGaussNukeProjectile>()) projectile.ai[0] = -1f; } else if (projectile.type == ModContent.ProjectileType<AresGaussNukeProjectileBoom>()) projectile.Kill(); } } calamityGlobalNPC.newAI[2] = 0f; AIState = (float)Phase.Deathrays; // Cancel enrage state if Ares is enraged if (EnragedState == (float)Enraged.Yes) EnragedState = (float)Enraged.No; } } break; // Move close to target, reduce velocity when close enough, create telegraph beams, fire deathrays case (int)Phase.Deathrays: // Set flight time to max during Deathray Spiral if (Main.netMode != NetmodeID.Server) { if (!Main.player[Main.myPlayer].dead && Main.player[Main.myPlayer].active && Vector2.Distance(Main.player[Main.myPlayer].Center, NPC.Center) < DeathrayEnrageDistance) { Main.player[Main.myPlayer].Calamity().infiniteFlight = true; } } if (distanceFromTarget > deathrayDistanceGateValue && calamityGlobalNPC.newAI[3] == 0f) { Vector2 desiredVelocity2 = Vector2.Normalize(distanceFromDestination) * baseVelocity; NPC.SimpleFlyMovement(desiredVelocity2, baseAcceleration); } else { // Enrage if the target is more than the deathray length away if ((distanceFromTarget > DeathrayEnrageDistance || (CalamityWorld.LegendaryMode && revenge)) && EnragedState == (float)Enraged.No) { // Play enrage sound if (Main.player[Main.myPlayer].active && !Main.player[Main.myPlayer].dead && Vector2.Distance(Main.player[Main.myPlayer].Center, NPC.Center) < soundDistance) { SoundEngine.PlaySound(EnragedSound, Main.player[Main.myPlayer].Center); } // Draedon comments on how foolish it is to run if (Main.netMode != NetmodeID.MultiplayerClient) CalamityUtils.DisplayLocalizedText("Mods.CalamityMod.Status.Boss.DraedonAresEnrageText", Draedon.TextColor); // Enrage EnragedState = (float)Enraged.Yes; } calamityGlobalNPC.newAI[3] = 1f; NPC.velocity *= decelerationVelocityMult; int totalProjectiles = bossRush ? 12 : death ? 10 : revenge ? 9 : expertMode ? 8 : 6; if (Main.getGoodWorld) totalProjectiles += 4; float radians = MathHelper.TwoPi / totalProjectiles; bool normalLaserRotation = NPC.localAI[0] % 2f == 0f; float velocity = 6f; double angleA = radians * 0.5; double angleB = MathHelper.ToRadians(90f) - angleA; float velocityX2 = (float)(velocity * Math.Sin(angleA) / Math.Sin(angleB)); Vector2 spinningPoint = normalLaserRotation ? new Vector2(0f, -velocity) : new Vector2(-velocityX2, -velocity); spinningPoint.Normalize(); float deathrayTelegraphDuration = bossRush ? deathrayTelegraphDuration_BossRush : death ? deathrayTelegraphDuration_Death : revenge ? deathrayTelegraphDuration_Rev : expertMode ? deathrayTelegraphDuration_Expert : deathrayTelegraphDuration_Normal; calamityGlobalNPC.newAI[2] += (EnragedState == (float)Enraged.Yes && calamityGlobalNPC.newAI[2] % 2f == 0f) ? 2f : 1f; if (calamityGlobalNPC.newAI[2] < deathrayTelegraphDuration) { // Fire deathray telegraph beams if (calamityGlobalNPC.newAI[2] == 1f) { // Despawn stupid fucking dog shit to avoid screaming the word "cunt", again for (int x = 0; x < Main.maxProjectiles; x++) { Projectile projectile = Main.projectile[x]; if (projectile.active) { if (projectile.type == ModContent.ProjectileType<AresTeslaOrb>() || projectile.type == ModContent.ProjectileType<AresPlasmaFireball>() || projectile.type == ModContent.ProjectileType<AresPlasmaBolt>() || projectile.type == ModContent.ProjectileType<AresGaussNukeProjectile>() || projectile.type == ModContent.ProjectileType<AresGaussNukeProjectileSpark>()) { if (projectile.timeLeft > 15) projectile.timeLeft = 15; if (projectile.type == ModContent.ProjectileType<AresPlasmaFireball>()) { projectile.ai[0] = -1f; projectile.ai[1] = -1f; } else if (projectile.type == ModContent.ProjectileType<AresGaussNukeProjectile>()) projectile.ai[0] = -1f; } else if (projectile.type == ModContent.ProjectileType<AresGaussNukeProjectileBoom>()) projectile.Kill(); } } // Set frames to deathray charge up frames, which begin on frame 12 // Reset the frame counter NPC.frameCounter = 0D; // X = 1 sets to frame 8 frameX = 1; // Y = 4 sets to frame 12 frameY = 4; // Create a bunch of lightning bolts in the sky ExoMechsSky.CreateLightningBolt(12); SoundEngine.PlaySound(CommonCalamitySounds.LaserCannonSound, NPC.Center); if (Main.netMode != NetmodeID.MultiplayerClient) { int type = ModContent.ProjectileType<AresDeathBeamTelegraph>(); Vector2 spawnPoint = NPC.Center + new Vector2(-1f, 23f); for (int k = 0; k < totalProjectiles; k++) { Vector2 laserVelocity = spinningPoint.RotatedBy(radians * k); Projectile.NewProjectile(NPC.GetSource_FromAI(), spawnPoint + Vector2.Normalize(laserVelocity) * 17f, laserVelocity, type, 0, 0f, Main.myPlayer, 0f, NPC.whoAmI); } } } } else { // Fire deathrays if (calamityGlobalNPC.newAI[2] == deathrayTelegraphDuration) { DeathraySoundSlot = SoundEngine.PlaySound(LaserStartSound, NPC.Center); if (Main.netMode != NetmodeID.MultiplayerClient) { int type = ModContent.ProjectileType<AresDeathBeamStart>(); int damage = NPC.GetProjectileDamage(type); Vector2 spawnPoint = NPC.Center + new Vector2(-1f, 23f); for (int k = 0; k < totalProjectiles; k++) { Vector2 laserVelocity = spinningPoint.RotatedBy(radians * k); Projectile.NewProjectile(NPC.GetSource_FromAI(), spawnPoint + Vector2.Normalize(laserVelocity) * 35f, laserVelocity, type, damage, 0f, Main.myPlayer, 0f, NPC.whoAmI); } } } } // Update the deathray sound if it's being played. if (SoundEngine.TryGetActiveSound(DeathraySoundSlot, out var deathraySound) && deathraySound.IsPlaying) deathraySound.Position = NPC.Center; if (calamityGlobalNPC.newAI[2] >= deathrayTelegraphDuration) { // Start the loop sound if the start sound finished. if (deathraySound is null || !deathraySound.IsPlaying || calamityGlobalNPC.newAI[2] == deathrayTelegraphDuration + 180f) { if (deathraySound is null || deathraySound.Style == LaserStartSound) { deathraySound?.Stop(); DeathraySoundSlot = SoundEngine.PlaySound(LaserLoopSound, NPC.Center); } else if (deathraySound is not null) deathraySound.Resume(); } } if (calamityGlobalNPC.newAI[2] >= deathrayTelegraphDuration + deathrayDuration) { if (!Main.zenithWorld || exoMechdusa) { AIState = (float)Phase.Normal; calamityGlobalNPC.newAI[2] = 0f; calamityGlobalNPC.newAI[3] = 0f; /* Normal positions: Laser = 0, Tesla = 1, Plasma = 2, Gauss = 3 * 0 = Laser = 0, Tesla = 1, Plasma = 2, Gauss = 3 * 1 = Laser = 3, Tesla = 1, Plasma = 2, Gauss = 0 * 2 = Laser = 3, Tesla = 2, Plasma = 1, Gauss = 0 * 3 = Laser = 0, Tesla = 2, Plasma = 1, Gauss = 3 * 4 = Laser = 0, Tesla = 1, Plasma = 2, Gauss = 3 * 5 = Laser = 3, Tesla = 1, Plasma = 2, Gauss = 0 */ if (revenge) { NPC.ai[3] += 1f + Main.rand.Next(2); if (NPC.ai[3] > 5f) NPC.ai[3] -= 4f; } else if (expertMode) { NPC.ai[3] += Main.rand.Next(2); if (NPC.ai[3] > 3f) NPC.ai[3] -= 2f; } } else { // Despawn stupid fucking dog shit to avoid screaming the word "cunt" for (int x = 0; x < Main.maxProjectiles; x++) { Projectile projectile = Main.projectile[x]; if (projectile.active) { if (projectile.type == ModContent.ProjectileType<AresTeslaOrb>() || projectile.type == ModContent.ProjectileType<AresPlasmaFireball>() || projectile.type == ModContent.ProjectileType<AresPlasmaBolt>() || projectile.type == ModContent.ProjectileType<AresGaussNukeProjectile>() || projectile.type == ModContent.ProjectileType<AresGaussNukeProjectileSpark>()) { if (projectile.timeLeft > 15) projectile.timeLeft = 15; if (projectile.type == ModContent.ProjectileType<AresPlasmaFireball>()) { projectile.ai[0] = -1f; projectile.ai[1] = -1f; } else if (projectile.type == ModContent.ProjectileType<AresGaussNukeProjectile>()) projectile.ai[0] = -1f; } else if (projectile.type == ModContent.ProjectileType<AresGaussNukeProjectileBoom>()) projectile.Kill(); } } calamityGlobalNPC.newAI[2] = 0f; calamityGlobalNPC.newAI[3] = 0f; // Cancel enrage state if Ares is enraged if (EnragedState == (float)Enraged.Yes) EnragedState = (float)Enraged.No; } // Stop the laser loop and play the end sound. deathraySound?.Stop(); SoundEngine.PlaySound(LaserEndSound, NPC.Center); NPC.localAI[0] += 1f; NPC.TargetClosest(); NPC.netUpdate = true; } } break; } } public override bool CanHitPlayer(Player target, ref int cooldownSlot) => false; public override bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position) { scale = 2f; return null; } public override void FindFrame(int frameHeight) { if (NPC.IsABestiaryIconDummy) NPC.Opacity = 1f; // Use telegraph frames when using deathrays NPC.frameCounter += 1D; if ((AIState == (float)Phase.Normal || NPC.Calamity().newAI[3] == 0f) && !NPC.IsABestiaryIconDummy) { if (NPC.frameCounter >= 6D) { // Reset frame counter NPC.frameCounter = 0D; // Increment the Y frame frameY++; // Reset the Y frame if greater than 8 if (frameY == maxFramesY) { frameX++; frameY = 0; } // Reset the frames to frame 0 if ((frameX * maxFramesY) + frameY > normalFrameLimit) frameX = frameY = 0; } } else { if (NPC.frameCounter >= 6D) { // Reset frame counter NPC.frameCounter = 0D; // Increment the Y frame frameY++; // Reset the Y frame if greater than 8 if (frameY == maxFramesY) { frameX++; frameY = 0; } // Reset the frames to frame 36, the start of the deathray firing animation loop if ((frameX * maxFramesY) + frameY > finalStageDeathrayChargeFrameLimit) frameX = frameY = 4; } } NPC.frame = new Rectangle(NPC.width * frameX, NPC.height * frameY, NPC.width, NPC.height); } public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) { // Draw the enrage smoke behind Ares SmokeDrawer.DrawSet(NPC.Center); // Draw arms. int laserArm = NPC.FindFirstNPC(ModContent.NPCType<AresLaserCannon>()); int gaussArm = NPC.FindFirstNPC(ModContent.NPCType<AresGaussNuke>()); int teslaArm = NPC.FindFirstNPC(ModContent.NPCType<AresTeslaCannon>()); int plasmaArm = NPC.FindFirstNPC(ModContent.NPCType<AresPlasmaFlamethrower>()); Color afterimageBaseColor = EnragedState == (float)Enraged.Yes ? Color.Red : Color.White; Color armGlowmaskColor = afterimageBaseColor; armGlowmaskColor.A = 184; (int, bool)[] armProperties = new (int, bool)[] { // Laser arm. (-1, true), // Gauss arm. (1, true), // Telsa arm. (-1, false), // Plasma arm. (1, false), }; // Swap out arm positions as necessary. // Normal Position: Laser, Tesla, Plasma, Laser switch ((int)NPC.ai[3]) { case 0: if (AIState == (int)Phase.Deathrays) { CalamityUtils.SwapArrayIndices(ref armProperties, 1, 3); CalamityUtils.SwapArrayIndices(ref armProperties, 0, 1); } break; case 1: CalamityUtils.SwapArrayIndices(ref armProperties, 0, 1); if (AIState == (int)Phase.Deathrays) CalamityUtils.SwapArrayIndices(ref armProperties, 0, 3); break; case 2: if (AIState != (int)Phase.Deathrays) { CalamityUtils.SwapArrayIndices(ref armProperties, 0, 1); CalamityUtils.SwapArrayIndices(ref armProperties, 2, 3); } else { CalamityUtils.SwapArrayIndices(ref armProperties, 0, 1); CalamityUtils.SwapArrayIndices(ref armProperties, 2, 3); CalamityUtils.SwapArrayIndices(ref armProperties, 0, 2); } break; case 3: CalamityUtils.SwapArrayIndices(ref armProperties, 2, 3); break; case 4: CalamityUtils.SwapArrayIndices(ref armProperties, 1, 3); break; case 5: if (AIState != (int)Phase.Deathrays) CalamityUtils.SwapArrayIndices(ref armProperties, 0, 1); else { CalamityUtils.SwapArrayIndices(ref armProperties, 0, 3); CalamityUtils.SwapArrayIndices(ref armProperties, 1, 3); } break; } // Create hulking arms that attach to all cannons. if (laserArm != -1) DrawArm(spriteBatch, Main.npc[laserArm].Center, screenPos, armGlowmaskColor, armProperties[0].Item1, armProperties[0].Item2); if (gaussArm != -1) DrawArm(spriteBatch, Main.npc[gaussArm].Center, screenPos, armGlowmaskColor, armProperties[1].Item1, armProperties[1].Item2); if (teslaArm != -1) DrawArm(spriteBatch, Main.npc[teslaArm].Center, screenPos, armGlowmaskColor, armProperties[2].Item1, armProperties[2].Item2); if (plasmaArm != -1) DrawArm(spriteBatch, Main.npc[plasmaArm].Center, screenPos, armGlowmaskColor, armProperties[3].Item1, armProperties[3].Item2); // Draw fake arms if Ares is being drawn as a bestiary icon. if (NPC.IsABestiaryIconDummy) { DrawArm(spriteBatch, NPC.Center + NPC.scale * new Vector2(-300f, 200f), screenPos, armGlowmaskColor, -1, true); DrawArm(spriteBatch, NPC.Center + NPC.scale * new Vector2(-400f, 300f), screenPos, armGlowmaskColor, -1, false); DrawArm(spriteBatch, NPC.Center + NPC.scale * new Vector2(300f, 200f), screenPos, armGlowmaskColor, 1, true); DrawArm(spriteBatch, NPC.Center + NPC.scale * new Vector2(400f, 300f), screenPos, armGlowmaskColor, 1, false); } Texture2D texture = TextureAssets.Npc[NPC.type].Value; Rectangle frame = new Rectangle(NPC.width * frameX, NPC.height * frameY, NPC.width, NPC.height); Vector2 vector = new Vector2(NPC.width / 2, NPC.height / 2); int numAfterimages = 5; if (CalamityConfig.Instance.Afterimages) { for (int i = 1; i < numAfterimages; i += 2) { Color afterimageColor = drawColor; afterimageColor = Color.Lerp(afterimageColor, afterimageBaseColor, 0.5f); afterimageColor = NPC.GetAlpha(afterimageColor); afterimageColor *= (numAfterimages - i) / 15f; Vector2 afterimageCenter = NPC.oldPos[i] + new Vector2(NPC.width, NPC.height) / 2f - screenPos; afterimageCenter -= new Vector2(texture.Width, texture.Height) / new Vector2(maxFramesX, maxFramesY) * NPC.scale / 2f; afterimageCenter += vector * NPC.scale + new Vector2(0f, NPC.gfxOffY); spriteBatch.Draw(texture, afterimageCenter, NPC.frame, afterimageColor, NPC.oldRot[i], vector, NPC.scale, SpriteEffects.None, 0f); } } Vector2 center = NPC.Center - screenPos; spriteBatch.Draw(texture, center, frame, NPC.GetAlpha(drawColor), NPC.rotation, vector, NPC.scale, SpriteEffects.None, 0f); texture = GlowTexture.Value; if (CalamityConfig.Instance.Afterimages) { for (int i = 1; i < numAfterimages; i += 2) { Color afterimageColor = drawColor; afterimageColor = Color.Lerp(afterimageColor, afterimageBaseColor, 0.5f); afterimageColor = NPC.GetAlpha(afterimageColor); afterimageColor *= (numAfterimages - i) / 15f; Vector2 afterimageCenter = NPC.oldPos[i] + new Vector2(NPC.width, NPC.height) / 2f - screenPos; afterimageCenter -= new Vector2(texture.Width, texture.Height) / new Vector2(maxFramesX, maxFramesY) * NPC.scale / 2f; afterimageCenter += vector * NPC.scale + new Vector2(0f, NPC.gfxOffY); spriteBatch.Draw(texture, afterimageCenter, NPC.frame, afterimageColor, NPC.oldRot[i], vector, NPC.scale, SpriteEffects.None, 0f); } } spriteBatch.Draw(texture, center, frame, afterimageBaseColor * NPC.Opacity, NPC.rotation, vector, NPC.scale, SpriteEffects.None, 0f); // Draw Aergia Neuron boobs if Exo Mechdusa if (exoMechdusa) { Texture2D neurontexture = ModContent.Request<Texture2D>("CalamityMod/NPCs/ExoMechs/AergiaNeuron").Value; Texture2D glowtexture = ModContent.Request<Texture2D>("CalamityMod/NPCs/ExoMechs/AergiaNeuron_Glow").Value; Vector2 NeuronRight = new Vector2(NPC.Center.X + 40, NPC.Center.Y + 50); Vector2 NeuronLeft = new Vector2(NPC.Center.X - 40, NPC.Center.Y + 50); Vector2 origin = new Vector2((float)(neurontexture.Width / 2), (float)(neurontexture.Height / 2)); spriteBatch.Draw(neurontexture, NeuronRight - Main.screenPosition, null, NPC.GetAlpha(drawColor), NPC.rotation, origin, NPC.scale, SpriteEffects.None, 0f); spriteBatch.Draw(neurontexture, NeuronLeft - Main.screenPosition, null, NPC.GetAlpha(drawColor), NPC.rotation, origin, NPC.scale, SpriteEffects.None, 0f); spriteBatch.Draw(glowtexture, NeuronRight - Main.screenPosition, null, Color.White, NPC.rotation, origin, NPC.scale, SpriteEffects.None, 0f); spriteBatch.Draw(glowtexture, NeuronLeft - Main.screenPosition, null, Color.White, NPC.rotation, origin, NPC.scale, SpriteEffects.None, 0f); } return false; } internal float WidthFunction(float completionRatio) { return MathHelper.Lerp(0.5f, 1.3f, (float)Math.Sin(MathHelper.Pi * completionRatio)) * NPC.scale; } internal Color ColorFunction(float completionRatio) { Color baseColor1 = EnragedState == (float)Enraged.Yes ? Color.Red : Color.Cyan; Color baseColor2 = EnragedState == (float)Enraged.Yes ? Color.IndianRed : Color.Cyan; float fadeToWhite = MathHelper.Lerp(0f, 0.65f, (float)Math.Sin(MathHelper.TwoPi * completionRatio + Main.GlobalTimeWrappedHourly * 4f) * 0.5f + 0.5f); Color baseColor = Color.Lerp(baseColor1, Color.White, fadeToWhite); Color color = Color.Lerp(baseColor, baseColor2, ((float)Math.Sin(MathHelper.Pi * completionRatio + Main.GlobalTimeWrappedHourly * 4f) * 0.5f + 0.5f) * 0.8f) * 0.65f; color.A = 84; if (NPC.Opacity <= 0f) return Color.Transparent; return color; } internal float BackgroundWidthFunction(float completionRatio) => WidthFunction(completionRatio) * 4f; public Color BackgroundColorFunction(float completionRatio) { Color backgroundColor = EnragedState == (float)Enraged.Yes ? Color.Crimson : Color.CornflowerBlue; Color color = backgroundColor * NPC.Opacity * 0.4f; return color; } public void DrawArm(SpriteBatch spriteBatch, Vector2 handPosition, Vector2 screenOffset, Color glowmaskColor, int direction, bool backArm) { SpriteEffects spriteDirection = direction == 1 ? SpriteEffects.None : SpriteEffects.FlipHorizontally; float distanceFromHand = NPC.Distance(handPosition); float frameTime = Main.GlobalTimeWrappedHourly * 0.9f % 1f; // Draw back arms. if (backArm) { Texture2D shoulderTexture = ArmTopShoulderTexture.Value; Texture2D armTexture1 = ArmTopTexture.Value; Texture2D armSegmentTexture = ArmSegmentTexture.Value; Texture2D armTexture2 = ArmTopTexture2.Value; Texture2D shoulderGlowmask = ArmTopShoulderTexture_Glow.Value; Texture2D armSegmentGlowmask = ArmSegmentTexture_Glow.Value; Texture2D armGlowmask2 = ArmTopTexture2_Glow.Value; Vector2 shoulderDrawPosition = NPC.Center + NPC.scale * new Vector2(direction * 176f, -100f); Vector2 arm1DrawPosition = shoulderDrawPosition + NPC.scale * new Vector2(direction * (shoulderTexture.Width + 16f), 10f); Vector2 armSegmentDrawPosition = arm1DrawPosition; // Determine frames. Rectangle shoulderFrame = shoulderTexture.Frame(1, 9, 0, (int)(frameTime * 9f)); Rectangle armSegmentFrame = armSegmentTexture.Frame(1, 9, 0, (int)(frameTime * 9f)); Rectangle arm2Frame = armTexture2.Frame(1, 9, 0, (int)(frameTime * 9f)); Vector2 arm1Origin = armTexture1.Size() * new Vector2((direction == 1).ToInt(), 0.5f); Vector2 arm2Origin = arm2Frame.Size() * new Vector2((direction == 1).ToInt(), 0.5f); float arm1Rotation = MathHelper.Clamp(distanceFromHand * direction / 1200f, -0.12f, 0.12f); float arm2Rotation = (handPosition - armSegmentDrawPosition - Vector2.UnitY * 12f).ToRotation(); if (direction == 1) arm2Rotation += MathHelper.Pi; float armSegmentRotation = arm2Rotation; // Handle offsets for points. armSegmentDrawPosition += arm1Rotation.ToRotationVector2() * NPC.scale * direction * -14f; armSegmentDrawPosition -= arm2Rotation.ToRotationVector2() * NPC.scale * direction * 20f; Vector2 arm2DrawPosition = armSegmentDrawPosition; arm2DrawPosition -= arm2Rotation.ToRotationVector2() * direction * NPC.scale * 40f; arm2DrawPosition += (arm2Rotation - MathHelper.PiOver2).ToRotationVector2() * NPC.scale * 14f; // Calculate colors. Color shoulderLightColor = NPC.GetAlpha(Lighting.GetColor((int)shoulderDrawPosition.X / 16, (int)shoulderDrawPosition.Y / 16)); Color arm1LightColor = NPC.GetAlpha(Lighting.GetColor((int)arm1DrawPosition.X / 16, (int)arm1DrawPosition.Y / 16)); Color armSegmentLightColor = NPC.GetAlpha(Lighting.GetColor((int)armSegmentDrawPosition.X / 16, (int)armSegmentDrawPosition.Y / 16)); Color arm2LightColor = NPC.GetAlpha(Lighting.GetColor((int)arm2DrawPosition.X / 16, (int)arm2DrawPosition.Y / 16)); Color glowmaskAlphaColor = NPC.GetAlpha(glowmaskColor); // Draw electricity between arms. if (NPC.Opacity > 0f && !NPC.IsABestiaryIconDummy) { List<Vector2> arm2ElectricArcPoints = AresTeslaOrb.DetermineElectricArcPoints(armSegmentDrawPosition, arm2DrawPosition + arm2Rotation.ToRotationVector2() * -direction * 20f, 250290787); PrimitiveRenderer.RenderTrail(arm2ElectricArcPoints, new(BackgroundWidthFunction, BackgroundColorFunction, smoothen: false), 90); PrimitiveRenderer.RenderTrail(arm2ElectricArcPoints, new(WidthFunction, ColorFunction, smoothen: false), 90); // Draw electricity between the final arm and the hand. List<Vector2> handElectricArcPoints = AresTeslaOrb.DetermineElectricArcPoints(arm2DrawPosition - arm2Rotation.ToRotationVector2() * direction * 100f, handPosition, 27182); PrimitiveRenderer.RenderTrail(handElectricArcPoints, new(BackgroundWidthFunction, BackgroundColorFunction, smoothen: false), 90); PrimitiveRenderer.RenderTrail(handElectricArcPoints, new(WidthFunction, ColorFunction, smoothen: false), 90); } shoulderDrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; arm1DrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; armSegmentDrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; arm2DrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; spriteBatch.Draw(armTexture1, arm1DrawPosition, null, arm1LightColor, arm1Rotation, arm1Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(shoulderTexture, shoulderDrawPosition, shoulderFrame, shoulderLightColor, 0f, shoulderFrame.Size() * 0.5f, NPC.scale, spriteDirection, 0f); spriteBatch.Draw(shoulderGlowmask, shoulderDrawPosition, shoulderFrame, glowmaskAlphaColor, 0f, shoulderFrame.Size() * 0.5f, NPC.scale, spriteDirection, 0f); spriteBatch.Draw(armSegmentTexture, armSegmentDrawPosition, armSegmentFrame, armSegmentLightColor, armSegmentRotation, armSegmentFrame.Size() * 0.5f, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(armSegmentGlowmask, armSegmentDrawPosition, armSegmentFrame, glowmaskAlphaColor, armSegmentRotation, armSegmentFrame.Size() * 0.5f, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(armTexture2, arm2DrawPosition, arm2Frame, arm2LightColor, arm2Rotation, arm2Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipVertically, 0f); spriteBatch.Draw(armGlowmask2, arm2DrawPosition, arm2Frame, glowmaskAlphaColor, arm2Rotation, arm2Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipVertically, 0f); } else { Texture2D shoulderTexture = ArmBottomShoulderTexture.Value; Texture2D connectorTexture = ArmBottomConnectorTexture.Value; Texture2D armTexture1 = ArmBottomTexture.Value; Texture2D armTexture2 = ArmBottomTexture2.Value; Texture2D shoulderGlowmask = ArmBottomShoulderTexture_Glow.Value; Texture2D armTexture1Glowmask = ArmBottomTexture_Glow.Value; Texture2D armTexture2Glowmask = ArmBottomTexture2_Glow.Value; Vector2 shoulderDrawPosition = NPC.Center + NPC.scale * new Vector2(direction * 110f, -54f); Vector2 connectorDrawPosition = shoulderDrawPosition + NPC.scale * new Vector2(direction * 20f, 32f); Vector2 arm1DrawPosition = shoulderDrawPosition + NPC.scale * Vector2.UnitX * direction * 20f; // Determine frames. Rectangle arm1Frame = armTexture1.Frame(1, 9, 0, (int)(frameTime * 9f)); Rectangle shoulderFrame = shoulderTexture.Frame(1, 9, 0, (int)(frameTime * 9f)); Rectangle arm2Frame = armTexture2.Frame(1, 9, 0, (int)(frameTime * 9f)); Vector2 arm1Origin = arm1Frame.Size() * new Vector2((direction == 1).ToInt(), 0.5f); Vector2 arm2Origin = arm2Frame.Size() * new Vector2((direction == 1).ToInt(), 0.5f); float arm1Rotation = CalamityUtils.WrapAngle90Degrees((handPosition - shoulderDrawPosition).ToRotation()) * 0.5f; connectorDrawPosition += arm1Rotation.ToRotationVector2() * NPC.scale * direction * -26f; arm1DrawPosition += arm1Rotation.ToRotationVector2() * NPC.scale * direction * (armTexture1.Width - 14f); float arm2Rotation = CalamityUtils.WrapAngle90Degrees((handPosition - arm1DrawPosition).ToRotation()); Vector2 arm2DrawPosition = arm1DrawPosition + arm2Rotation.ToRotationVector2() * NPC.scale * direction * (armTexture2.Width + 16f) - Vector2.UnitY * 16f; // Calculate colors. Color shoulderLightColor = NPC.GetAlpha(Lighting.GetColor((int)shoulderDrawPosition.X / 16, (int)shoulderDrawPosition.Y / 16)); Color arm1LightColor = NPC.GetAlpha(Lighting.GetColor((int)arm1DrawPosition.X / 16, (int)arm1DrawPosition.Y / 16)); Color arm2LightColor = NPC.GetAlpha(Lighting.GetColor((int)arm2DrawPosition.X / 16, (int)arm2DrawPosition.Y / 16)); Color glowmaskAlphaColor = NPC.GetAlpha(glowmaskColor); // Draw electricity between arms. if (NPC.Opacity > 0f && !NPC.IsABestiaryIconDummy) { List<Vector2> arm2ElectricArcPoints = AresTeslaOrb.DetermineElectricArcPoints(arm1DrawPosition - arm2Rotation.ToRotationVector2() * direction * 10f, arm1DrawPosition + arm2Rotation.ToRotationVector2() * direction * 20f, 31416); PrimitiveRenderer.RenderTrail(arm2ElectricArcPoints, new(BackgroundWidthFunction, BackgroundColorFunction, smoothen: false), 90); PrimitiveRenderer.RenderTrail(arm2ElectricArcPoints, new(WidthFunction, ColorFunction, smoothen: false), 90); // Draw electricity between the final arm and the hand. List<Vector2> handElectricArcPoints = AresTeslaOrb.DetermineElectricArcPoints(arm2DrawPosition - arm2Rotation.ToRotationVector2() * direction * 20f, handPosition, 27182); PrimitiveRenderer.RenderTrail(handElectricArcPoints, new(BackgroundWidthFunction, BackgroundColorFunction, smoothen: false), 90); PrimitiveRenderer.RenderTrail(handElectricArcPoints, new(WidthFunction, ColorFunction, smoothen: false), 90); } shoulderDrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; connectorDrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; arm1DrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; arm2DrawPosition += Vector2.UnitY * NPC.gfxOffY - screenOffset; spriteBatch.Draw(shoulderTexture, shoulderDrawPosition, shoulderFrame, shoulderLightColor, arm1Rotation, shoulderFrame.Size() * 0.5f, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(shoulderGlowmask, shoulderDrawPosition, shoulderFrame, glowmaskAlphaColor, arm1Rotation, shoulderFrame.Size() * 0.5f, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(connectorTexture, connectorDrawPosition, null, shoulderLightColor, 0f, connectorTexture.Size() * 0.5f, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(armTexture1, arm1DrawPosition, arm1Frame, arm1LightColor, arm1Rotation, arm1Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(armTexture1Glowmask, arm1DrawPosition, arm1Frame, glowmaskAlphaColor, arm1Rotation, arm1Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(armTexture2, arm2DrawPosition, arm2Frame, arm2LightColor, arm2Rotation, arm2Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); spriteBatch.Draw(armTexture2Glowmask, arm2DrawPosition, arm2Frame, glowmaskAlphaColor, arm2Rotation, arm2Origin, NPC.scale, spriteDirection ^ SpriteEffects.FlipHorizontally, 0f); } } public override void ModifyTypeName(ref string typeName) { if (exoMechdusa) { typeName = this.GetLocalizedValue("HekateName"); } } public override void BossLoot(ref string name, ref int potionType) { potionType = ModContent.ItemType<OmegaHealingPotion>(); } public override void OnKill() { // Check if the other exo mechs are alive bool exoWormAlive = false; bool exoTwinsAlive = false; if (SoundEngine.TryGetActiveSound(DeathraySoundSlot, out var deathraySound) && deathraySound.IsPlaying) deathraySound?.Stop(); if (CalamityGlobalNPC.draedonExoMechWorm != -1) { if (Main.npc[CalamityGlobalNPC.draedonExoMechWorm].active) exoWormAlive = true; } if (CalamityGlobalNPC.draedonExoMechTwinGreen != -1) { if (Main.npc[CalamityGlobalNPC.draedonExoMechTwinGreen].active) exoTwinsAlive = true; } // Check for Draedon bool draedonAlive = false; if (CalamityGlobalNPC.draedon != -1) { if (Main.npc[CalamityGlobalNPC.draedon].active) draedonAlive = true; } // Phase 5, when 1 mech dies and the other 2 return to fight if (exoWormAlive && exoTwinsAlive) { if (draedonAlive) { Main.npc[CalamityGlobalNPC.draedon].localAI[0] = 4f; Main.npc[CalamityGlobalNPC.draedon].ai[0] = Draedon.ExoMechPhaseDialogueTime; } } // Phase 7, when 1 mech dies and the final one returns to the fight else if (exoWormAlive || exoTwinsAlive) { if (draedonAlive) { Main.npc[CalamityGlobalNPC.draedon].localAI[0] = 6f; Main.npc[CalamityGlobalNPC.draedon].ai[0] = Draedon.ExoMechPhaseDialogueTime; } } else AresBody.DoMiscDeathEffects(NPC, MechType.Ares); } public override void ModifyNPCLoot(NPCLoot npcLoot) => DefineExoMechLoot(NPC, npcLoot, (int)MechType.Ares); public static bool CanDropLoot() { return NPC.CountNPCS(ModContent.NPCType<ThanatosHead>()) + NPC.CountNPCS(ModContent.NPCType<AresBody>()) + NPC.CountNPCS(ModContent.NPCType<Apollo.Apollo>()) <= 1; } public static void DoMiscDeathEffects(NPC npc, MechType mechType) { CalamityGlobalNPC.SetNewBossJustDowned(npc); switch (mechType) { case MechType.Thanatos: DownedBossSystem.downedThanatos = true; DownedBossSystem.downedExoMechs = true; break; case MechType.Ares: DownedBossSystem.downedAres = true; DownedBossSystem.downedExoMechs = true; break; case MechType.ArtemisAndApollo: DownedBossSystem.downedArtemisAndApollo = true; DownedBossSystem.downedExoMechs = true; break; } CalamityNetcode.SyncWorld(); } public static void DefineExoMechLoot(NPC npc, NPCLoot npcLoot, int mechType) { var mainDrops = npcLoot.DefineConditionalDropSet(CanDropLoot); LeadingConditionRule normalOnly = new LeadingConditionRule(new Conditions.NotExpert()); mainDrops.Add(normalOnly); bool ThanatosLoot(DropAttemptInfo info) => info.npc.type == ModContent.NPCType<ThanatosHead>() || DownedBossSystem.downedThanatos; bool AresLoot(DropAttemptInfo info) => info.npc.type == ModContent.NPCType<AresBody>() || DownedBossSystem.downedAres; bool ApolloLoot(DropAttemptInfo info) => info.npc.type == ModContent.NPCType<Apollo.Apollo>() || DownedBossSystem.downedArtemisAndApollo; // Trophies mainDrops.Add(ItemDropRule.ByCondition(DropHelper.If(info => info.npc.type == ModContent.NPCType<ThanatosHead>()), ModContent.ItemType<ThanatosTrophy>())); mainDrops.Add(ItemDropRule.ByCondition(DropHelper.If(info => info.npc.type == ModContent.NPCType<AresBody>()), ModContent.ItemType<AresTrophy>())); mainDrops.Add(ItemDropRule.ByCondition(DropHelper.If(info => info.npc.type == ModContent.NPCType<Apollo.Apollo>()), ModContent.ItemType<ArtemisTrophy>())); mainDrops.Add(ItemDropRule.ByCondition(DropHelper.If(info => info.npc.type == ModContent.NPCType<Apollo.Apollo>()), ModContent.ItemType<ApolloTrophy>())); // Relic npcLoot.DefineConditionalDropSet(DropHelper.RevAndMaster).AddIf(CanDropLoot, ModContent.ItemType<DraedonRelic>()); // GFB Broken Water Filter var GFBOnly = npcLoot.DefineConditionalDropSet(DropHelper.GFB); { GFBOnly.Add(ModContent.ItemType<BrokenWaterFilter>(), hideLootReport: true); } // Lore item mainDrops.Add(ItemDropRule.ByCondition(DropHelper.If(() => !DownedBossSystem.downedExoMechs, desc: DropHelper.FirstKillText), ModContent.ItemType<LoreExoMechs>())); // Cynosure: If SCal has been defeated and this is the first kill of the Exo Mechs, drop the special lore item mainDrops.Add(ItemDropRule.ByCondition( DropHelper.If( () => !DownedBossSystem.downedExoMechs && DownedBossSystem.downedCalamitas, desc: DropHelper.CynosureText), ModContent.ItemType<LoreCynosure>() )); // Treasure bag npcLoot.Add(ItemDropRule.BossBagByCondition(DropHelper.If(CanDropLoot), ModContent.ItemType<DraedonBag>())); // Legendary seed soup mainDrops.Add(ItemDropRule.ByCondition(DropHelper.If(info => info.npc.type == ModContent.NPCType<AresBody>() && info.npc.ModNPC<Ares.AresBody>().exoMechdusa), ModContent.ItemType<LavaChickenBroth>()), hideLootReport: true); // All other drops are contained in the bag, so they only drop directly on Normal if (!Main.expertMode) { // Materials normalOnly.Add(ModContent.ItemType<ExoPrism>(), 1, 25, 30); // Weapons // Higher chance due to how the drops work // Thanatos weapons normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ThanatosLoot), ModContent.ItemType<SpineOfThanatos>())); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ThanatosLoot), ModContent.ItemType<RefractionRotor>())); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ThanatosLoot), ModContent.ItemType<AtlasMunitionsBeacon>())); // Ares weapons normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(AresLoot), ModContent.ItemType<PhotonRipper>())); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(AresLoot), ModContent.ItemType<TheJailor>())); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(AresLoot), ModContent.ItemType<AresExoskeleton>())); // Twins weapons normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ApolloLoot), ModContent.ItemType<TheAtomSplitter>())); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ApolloLoot), ModContent.ItemType<SurgeDriver>())); // Equipment normalOnly.Add(ModContent.ItemType<ExoThrone>()); normalOnly.Add(ModContent.ItemType<DraedonsHeart>()); // Vanity // Higher chance due to how the drops work normalOnly.Add(ModContent.ItemType<DraedonMask>(), 3); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ThanatosLoot), ModContent.ItemType<ThanatosMask>(), 7, chanceNumerator: 2)); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(AresLoot), ModContent.ItemType<AresMask>(), 7, chanceNumerator: 2)); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ApolloLoot), ModContent.ItemType<ArtemisMask>(), 7, chanceNumerator: 2)); normalOnly.Add(ItemDropRule.ByCondition(DropHelper.If(ApolloLoot), ModContent.ItemType<ApolloMask>(), 7, chanceNumerator: 2)); normalOnly.Add(ModContent.ItemType<ThankYouPainting>(), ThankYouPainting.DropInt); } } public override void HitEffect(NPC.HitInfo hit) { for (int k = 0; k < 3; k++) Dust.NewDust(NPC.position, NPC.width, NPC.height, 107, 0f, 0f, 100, new Color(0, 255, 255), 1f); if (NPC.soundDelay == 0) { NPC.soundDelay = 3; SoundEngine.PlaySound(CommonCalamitySounds.ExoHitSound, NPC.Center); } if (NPC.life <= 0) { for (int i = 0; i < 2; i++) { Dust.NewDust(NPC.position, NPC.width, NPC.height, 107, 0f, 0f, 100, new Color(0, 255, 255), 1.5f); } for (int j = 0; j < 20; j++) { int plasmaDust = Dust.NewDust(NPC.position, NPC.width, NPC.height, 107, 0f, 0f, 0, new Color(0, 255, 255), 2.5f); Main.dust[plasmaDust].noGravity = true; Main.dust[plasmaDust].velocity *= 3f; plasmaDust = Dust.NewDust(NPC.position, NPC.width, NPC.height, 107, 0f, 0f, 100, new Color(0, 255, 255), 1.5f); Main.dust[plasmaDust].velocity *= 2f; Main.dust[plasmaDust].noGravity = true; } if (Main.netMode != NetmodeID.Server) { Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody1").Type, 1f); Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody2").Type, 1f); Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody3").Type, 1f); Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody4").Type, 1f); Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody5").Type, 1f); Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody6").Type, 1f); Gore.NewGore(NPC.GetSource_Death(), NPC.position, NPC.velocity, Mod.Find<ModGore>("AresBody7").Type, 1f); } } } public override bool CheckActive() => false; public override void ApplyDifficultyAndPlayerScaling(int numPlayers, float balance, float bossAdjustment) { NPC.lifeMax = (int)(NPC.lifeMax * 0.8f * balance * bossAdjustment); NPC.damage = (int)(NPC.damage * 0.8f); } } }
0
0.942093
1
0.942093
game-dev
MEDIA
0.984846
game-dev
0.698576
1
0.698576
WesJD/AnvilGUI
4,433
1_10_R1/src/main/java/net/wesjd/anvilgui/version/Wrapper1_10_R1.java
package net.wesjd.anvilgui.version; import net.minecraft.server.v1_10_R1.*; import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_10_R1.event.CraftEventFactory; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; /** * {@link VersionWrapper} implemented for NMS version 1_10_R1 * * @author Wesley Smith * @since 1.0 */ public class Wrapper1_10_R1 implements VersionWrapper { /** * {@inheritDoc} */ @Override public int getNextContainerId(Player player, AnvilContainerWrapper container) { return toNMS(player).nextContainerCounter(); } /** * {@inheritDoc} */ @Override public void handleInventoryCloseEvent(Player player) { CraftEventFactory.handleInventoryCloseEvent(toNMS(player)); toNMS(player).s(); // s -> doCloseContainer } /** * {@inheritDoc} */ @Override public void sendPacketOpenWindow(Player player, int containerId, Object guiTitle) { toNMS(player) .playerConnection .sendPacket(new PacketPlayOutOpenWindow( containerId, "minecraft:anvil", new ChatMessage(Blocks.ANVIL.a() + ".name"))); } /** * {@inheritDoc} */ @Override public void sendPacketCloseWindow(Player player, int containerId) { toNMS(player).playerConnection.sendPacket(new PacketPlayOutCloseWindow(containerId)); } /** * {@inheritDoc} */ @Override public void sendPacketExperienceChange(Player player, int experienceLevel) { toNMS(player).playerConnection.sendPacket(new PacketPlayOutExperience(0f, 0, experienceLevel)); } /** * {@inheritDoc} */ @Override public void setActiveContainerDefault(Player player) { toNMS(player).activeContainer = toNMS(player).defaultContainer; } /** * {@inheritDoc} */ @Override public void setActiveContainer(Player player, AnvilContainerWrapper container) { toNMS(player).activeContainer = (Container) container; } /** * {@inheritDoc} */ @Override public void setActiveContainerId(AnvilContainerWrapper container, int containerId) { ((Container) container).windowId = containerId; } /** * {@inheritDoc} */ @Override public void addActiveContainerSlotListener(AnvilContainerWrapper container, Player player) { ((Container) container).addSlotListener(toNMS(player)); } /** * {@inheritDoc} */ @Override public AnvilContainerWrapper newContainerAnvil(Player player, Object guiTitle) { return new Wrapper1_10_R1.AnvilContainer(toNMS(player)); } @Override public boolean isCustomTitleSupported() { return false; } @Override public Object literalChatComponent(String content) { return null; } @Override public Object jsonChatComponent(String json) { return null; } /** * Turns a {@link Player} into an NMS one * * @param player The player to be converted * @return the NMS EntityPlayer */ private EntityPlayer toNMS(Player player) { return ((CraftPlayer) player).getHandle(); } /** * Modifications to ContainerAnvil that makes it so you don't have to have xp to use this anvil */ private class AnvilContainer extends ContainerAnvil implements AnvilContainerWrapper { public AnvilContainer(EntityHuman entityhuman) { super(entityhuman.inventory, entityhuman.world, new BlockPosition(0, 0, 0), entityhuman); } @Override public void e() { // If the output is empty copy the left input into the output Slot output = this.getSlot(2); if (!output.hasItem()) { Slot input = this.getSlot(0); if (input.hasItem()) { output.set(input.getItem().cloneItemStack()); } } this.a = 0; // Sync to the client this.b(); } @Override public boolean a(EntityHuman entityhuman) { return true; } @Override public void b(EntityHuman entityhuman) {} @Override public Inventory getBukkitInventory() { return getBukkitView().getTopInventory(); } } }
0
0.913678
1
0.913678
game-dev
MEDIA
0.977608
game-dev
0.964963
1
0.964963
kniEngine/kni
2,745
Tests/Interactive/MacOS/SoundTest/Game1.cs
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace SoundTest { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D tExplosion; SoundEffect sExplosion; Random rnd = new Random(); class explosion { public Vector2 Position; public float Size; public explosion(Vector2 pos) { Position = pos; Size = 1f; } } List<explosion> Explosions = new List<explosion>(); TimeSpan timer = TimeSpan.Zero; int Interval = 1000; //Milliseconds. The duration of the sound is about 1.5 sec. public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = 1024;; graphics.PreferredBackBufferHeight = 768; graphics.IsFullScreen = false; } protected override void Initialize() { base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); sExplosion = Content.Load<SoundEffect>("ExplosionSound"); //sExplosion = Content.Load<SoundEffect>("laser1"); //sExplosion = Content.Load<SoundEffect>("FillingHoneyPot_Loop"); tExplosion = Content.Load<Texture2D>("Explosion"); } protected override void Update(GameTime gameTime) { base.Update(gameTime); //update explosions for (int i = 0; i<Explosions.Count;i++) { Explosions[i].Size -= 0.01f; if (Explosions[i].Size < 0.1f) { Explosions.RemoveAt(i); i--; } } //Check for next explosion timer += gameTime.ElapsedGameTime; if (timer.TotalMilliseconds > Interval) { timer = TimeSpan.Zero; float x = rnd.Next(24,1000); Explosions.Add(new explosion(new Vector2(x, rnd.Next(50,700)))); sExplosion.Play(1f, 1f, (x / 512f) -1); } //Check for exit KeyboardState state = new KeyboardState(); state = Keyboard.GetState(); if (state.IsKeyDown(Keys.Escape) || state.IsKeyDown(Keys.Space) || state.IsKeyDown(Keys.Enter)) this.Exit(); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); base.Draw(gameTime); spriteBatch.Begin(); //Draw explosions foreach (explosion e in Explosions) spriteBatch.Draw(tExplosion, e.Position, null, Color.White, 0, Vector2.Zero,e.Size, SpriteEffects.None, 1); spriteBatch.End(); } } }
0
0.748545
1
0.748545
game-dev
MEDIA
0.926843
game-dev
0.614786
1
0.614786
kmatheussen/radium
9,983
pluginhost/JuceLibraryCode/modules_old4/juce_gui_basics/commands/juce_ApplicationCommandTarget.h
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2022 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 7 End-User License Agreement and JUCE Privacy Policy. End User License Agreement: www.juce.com/juce-7-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== /** A command target publishes a list of command IDs that it can perform. An ApplicationCommandManager despatches commands to targets, which must be able to provide information about what commands they can handle. To create a target, you'll need to inherit from this class, implementing all of its pure virtual methods. For info about how a target is chosen to receive a command, see ApplicationCommandManager::getFirstCommandTarget(). @see ApplicationCommandManager, ApplicationCommandInfo @tags{GUI} */ class JUCE_API ApplicationCommandTarget { public: //============================================================================== /** Creates a command target. */ ApplicationCommandTarget(); /** Destructor. */ virtual ~ApplicationCommandTarget(); //============================================================================== /** Contains contextual details about the invocation of a command. */ struct JUCE_API InvocationInfo { //============================================================================== InvocationInfo (const CommandID commandID); //============================================================================== /** The UID of the command that should be performed. */ CommandID commandID; /** The command's flags. See ApplicationCommandInfo for a description of these flag values. */ int commandFlags; //============================================================================== /** The types of context in which the command might be called. */ enum InvocationMethod { direct = 0, /**< The command is being invoked directly by a piece of code. */ fromKeyPress, /**< The command is being invoked by a key-press. */ fromMenu, /**< The command is being invoked by a menu selection. */ fromButton /**< The command is being invoked by a button click. */ }; /** The type of event that triggered this command. */ InvocationMethod invocationMethod; //============================================================================== /** If triggered by a keypress or menu, this will be the component that had the keyboard focus at the time. If triggered by a button, it may be set to that component, or it may be null. */ Component* originatingComponent; //============================================================================== /** The keypress that was used to invoke it. Note that this will be an invalid keypress if the command was invoked by some other means than a keyboard shortcut. */ KeyPress keyPress; /** True if the callback is being invoked when the key is pressed, false if the key is being released. @see KeyPressMappingSet::addCommand() */ bool isKeyDown; /** If the key is being released, this indicates how long it had been held down for. (Only relevant if isKeyDown is false.) */ int millisecsSinceKeyPressed; }; //============================================================================== /** This must return the next target to try after this one. When a command is being sent, and the first target can't handle that command, this method is used to determine the next target that should be tried. It may return nullptr if it doesn't know of another target. If your target is a Component, you would usually use the findFirstTargetParentComponent() method to return a parent component that might want to handle it. @see invoke */ virtual ApplicationCommandTarget* getNextCommandTarget() = 0; /** This must return a complete list of commands that this target can handle. Your target should add all the command IDs that it handles to the array that is passed-in. */ virtual void getAllCommands (Array<CommandID>& commands) = 0; /** This must provide details about one of the commands that this target can perform. This will be called with one of the command IDs that the target provided in its getAllCommands() methods. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with suitable information about the command. (The commandID field will already have been filled-in by the caller). The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to set all the fields at once. If the command is currently inactive for some reason, this method must use ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled bit of the ApplicationCommandInfo::flags field). Any default key-presses for the command should be appended to the ApplicationCommandInfo::defaultKeypresses field. Note that if you change something that affects the status of the commands that would be returned by this method (e.g. something that makes some commands active or inactive), you should call ApplicationCommandManager::commandStatusChanged() to cause the manager to refresh its status. */ virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0; /** This must actually perform the specified command. If this target is able to perform the command specified by the commandID field of the InvocationInfo structure, then it should do so, and must return true. If it can't handle this command, it should return false, which tells the caller to pass the command on to the next target in line. @see invoke, ApplicationCommandManager::invoke */ virtual bool perform (const InvocationInfo& info) = 0; //============================================================================== /** Makes this target invoke a command. Your code can call this method to invoke a command on this target, but normally you'd call it indirectly via ApplicationCommandManager::invoke() or ApplicationCommandManager::invokeDirectly(). If this target can perform the given command, it will call its perform() method to do so. If not, then getNextCommandTarget() will be used to determine the next target to try, and the command will be passed along to it. @param invocationInfo this must be correctly filled-in, describing the context for the invocation. @param asynchronously if false, the command will be performed before this method returns. If true, a message will be posted so that the command will be performed later on the message thread, and this method will return immediately. @see perform, ApplicationCommandManager::invoke */ bool invoke (const InvocationInfo& invocationInfo, const bool asynchronously); /** Invokes a given command directly on this target. This is just an easy way to call invoke() without having to fill out the InvocationInfo structure. */ bool invokeDirectly (const CommandID commandID, const bool asynchronously); //============================================================================== /** Searches this target and all subsequent ones for the first one that can handle the specified command. This will use getNextCommandTarget() to determine the chain of targets to try after this one. */ ApplicationCommandTarget* getTargetForCommand (const CommandID commandID); /** Checks whether this command can currently be performed by this target. This will return true only if a call to getCommandInfo() doesn't set the isDisabled flag to indicate that the command is inactive. */ bool isCommandActive (const CommandID commandID); /** If this object is a Component, this method will search upwards in its current UI hierarchy for the next parent component that implements the ApplicationCommandTarget class. If your target is a Component, this is a very handy method to use in your getNextCommandTarget() implementation. */ ApplicationCommandTarget* findFirstTargetParentComponent(); private: //============================================================================== class CommandMessage; friend class CommandMessage; bool tryToInvoke (const InvocationInfo&, bool async); JUCE_DECLARE_WEAK_REFERENCEABLE (ApplicationCommandTarget) JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ApplicationCommandTarget) }; } // namespace juce
0
0.924634
1
0.924634
game-dev
MEDIA
0.307856
game-dev
0.693736
1
0.693736
pelya/openttd-android
7,289
src/saveload/settings_sl.cpp
/* * This file is part of OpenTTD. * OpenTTD 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, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file settings_sl.cpp Handles the saveload part of the settings. */ #include "../stdafx.h" #include "saveload.h" #include "compat/settings_sl_compat.h" #include "../settings_type.h" #include "../settings_table.h" #include "../network/network.h" #include "../fios.h" #include "../safeguards.h" /** * Prepare for reading and old diff_custom by zero-ing the memory. */ void PrepareOldDiffCustom() { memset(_old_diff_custom, 0, sizeof(_old_diff_custom)); } /** * Reading of the old diff_custom array and transforming it to the new format. * @param savegame is it read from the config or savegame. In the latter case * we are sure there is an array; in the former case we have * to check that. */ void HandleOldDiffCustom(bool savegame) { /* Savegames before v4 didn't have "town_council_tolerance" in savegame yet. */ bool has_no_town_council_tolerance = savegame && IsSavegameVersionBefore(SLV_4); uint options_to_load = GAME_DIFFICULTY_NUM - (has_no_town_council_tolerance ? 1 : 0); if (!savegame) { /* If we did read to old_diff_custom, then at least one value must be non 0. */ bool old_diff_custom_used = false; for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) { old_diff_custom_used = (_old_diff_custom[i] != 0); } if (!old_diff_custom_used) return; } /* Iterate over all the old difficulty settings, and convert the list-value to the new setting. */ uint i = 0; for (const auto &name : _old_diff_settings) { if (has_no_town_council_tolerance && name == "town_council_tolerance") continue; std::string fullname = "difficulty." + name; const SettingDesc *sd = GetSettingFromName(fullname); /* Some settings are no longer in use; skip reading those. */ if (sd == nullptr) { i++; continue; } int32 value = (int32)((name == "max_loan" ? 1000 : 1) * _old_diff_custom[i++]); sd->AsIntSetting()->MakeValueValidAndWrite(savegame ? &_settings_game : &_settings_newgame, value); } } /** * Get the SaveLoad description for the SettingTable. * @param settings SettingDesc struct containing all information. * @param is_loading True iff the SaveLoad table is for loading. * @return Vector with SaveLoad entries for the SettingTable. */ static std::vector<SaveLoad> GetSettingsDesc(const SettingTable &settings, bool is_loading) { std::vector<SaveLoad> saveloads; for (auto &desc : settings) { const SettingDesc *sd = GetSettingDesc(desc); if (sd->flags & SF_NOT_IN_SAVE) continue; if (is_loading && (sd->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server) { if (IsSavegameVersionBefore(SLV_TABLE_CHUNKS)) { /* We don't want to read this setting, so we do need to skip over it. */ saveloads.push_back({sd->GetName(), sd->save.cmd, GetVarFileType(sd->save.conv) | SLE_VAR_NULL, sd->save.length, sd->save.version_from, sd->save.version_to, 0, nullptr, 0, nullptr}); } continue; } saveloads.push_back(sd->save); } return saveloads; } /** * Save and load handler for settings * @param settings SettingDesc struct containing all information * @param object can be either nullptr in which case we load global variables or * a pointer to a struct which is getting saved */ static void LoadSettings(const SettingTable &settings, void *object, const SaveLoadCompatTable &slct) { const std::vector<SaveLoad> slt = SlCompatTableHeader(GetSettingsDesc(settings, true), slct); if (!IsSavegameVersionBefore(SLV_RIFF_TO_ARRAY) && SlIterateArray() == -1) return; SlObject(object, slt); if (!IsSavegameVersionBefore(SLV_RIFF_TO_ARRAY) && SlIterateArray() != -1) SlErrorCorrupt("Too many settings entries"); /* Ensure all IntSettings are valid (min/max could have changed between versions etc). */ for (auto &desc : settings) { const SettingDesc *sd = GetSettingDesc(desc); if (sd->flags & SF_NOT_IN_SAVE) continue; if ((sd->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server) continue; if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; if (sd->IsIntSetting()) { const IntSettingDesc *int_setting = sd->AsIntSetting(); int_setting->MakeValueValidAndWrite(object, int_setting->Read(object)); } } } /** * Save and load handler for settings * @param settings SettingDesc struct containing all information * @param object can be either nullptr in which case we load global variables or * a pointer to a struct which is getting saved */ static void SaveSettings(const SettingTable &settings, void *object) { const std::vector<SaveLoad> slt = GetSettingsDesc(settings, false); SlTableHeader(slt); SlSetArrayIndex(0); SlObject(object, slt); } struct OPTSChunkHandler : ChunkHandler { OPTSChunkHandler() : ChunkHandler('OPTS', CH_READONLY) {} void Load() const override { /* Copy over default setting since some might not get loaded in * a networking environment. This ensures for example that the local * autosave-frequency stays when joining a network-server */ PrepareOldDiffCustom(); LoadSettings(_old_gameopt_settings, &_settings_game, _gameopt_sl_compat); HandleOldDiffCustom(true); } }; struct PATSChunkHandler : ChunkHandler { PATSChunkHandler() : ChunkHandler('PATS', CH_TABLE) {} /** * Create a single table with all settings that should be stored/loaded * in the savegame. */ SettingTable GetSettingTable() const { static const SettingTable saveload_settings_tables[] = { _difficulty_settings, _economy_settings, _game_settings, _linkgraph_settings, _locale_settings, _pathfinding_settings, _script_settings, _world_settings, }; static std::vector<SettingVariant> settings_table; if (settings_table.empty()) { for (auto &saveload_settings_table : saveload_settings_tables) { for (auto &saveload_setting : saveload_settings_table) { settings_table.push_back(saveload_setting); } } } return settings_table; } void Load() const override { /* Copy over default setting since some might not get loaded in * a networking environment. This ensures for example that the local * currency setting stays when joining a network-server */ LoadSettings(this->GetSettingTable(), &_settings_game, _settings_sl_compat); } void LoadCheck(size_t) const override { LoadSettings(this->GetSettingTable(), &_load_check_data.settings, _settings_sl_compat); } void Save() const override { SaveSettings(this->GetSettingTable(), &_settings_game); } }; static const OPTSChunkHandler OPTS; static const PATSChunkHandler PATS; static const ChunkHandlerRef setting_chunk_handlers[] = { OPTS, PATS, }; extern const ChunkHandlerTable _setting_chunk_handlers(setting_chunk_handlers);
0
0.972195
1
0.972195
game-dev
MEDIA
0.600609
game-dev
0.90625
1
0.90625
livereload/livereload-plugins
1,144
SLIM.lrplugin/gem/gems/tilt-2.0.0/lib/tilt/liquid.rb
require 'tilt/template' require 'liquid' module Tilt # Liquid template implementation. See: # http://liquid.rubyforge.org/ # # Liquid is designed to be a *safe* template system and threfore # does not provide direct access to execuatable scopes. In order to # support a +scope+, the +scope+ must be able to represent itself # as a hash by responding to #to_h. If the +scope+ does not respond # to #to_h it will be ignored. # # LiquidTemplate does not support yield blocks. # # It's suggested that your program require 'liquid' at load # time when using this template engine. class LiquidTemplate < Template def prepare @engine = ::Liquid::Template.parse(data) end def evaluate(scope, locals, &block) locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } if scope.respond_to?(:to_h) scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } locals = scope.merge(locals) end locals['yield'] = block.nil? ? '' : yield locals['content'] = locals['yield'] @engine.render(locals) end def allows_script? false end end end
0
0.822876
1
0.822876
game-dev
MEDIA
0.328509
game-dev
0.595889
1
0.595889
liuhaopen/UnityMMO
1,584
Lua/Game/MainUI/MainUIRoleHeadView.lua
local MainUIRoleHeadView = BaseClass() function MainUIRoleHeadView:DefaultVar( ) return { UIConfig = { prefab_path = "Assets/AssetBundleRes/ui/mainui/MainUIRoleHeadView.prefab", canvas_name = "MainUI", components = { }, }, } end function MainUIRoleHeadView:OnLoad( ) local names = { "money_1","money_2","flag","head_icon:raw","lv:txt","lv_bg","blood_bar:img", } UI.GetChildren(self, self.transform, names) self:AddEvents() self:UpdateView() end function MainUIRoleHeadView:AddEvents( ) local HPChange = function ( curHp, maxHp ) self.blood_bar_img.fillAmount = Mathf.Clamp01(curHp/maxHp) end CSLuaBridge.GetInstance():SetLuaFunc2Num(GlobalEvents.MainRoleHPChanged, HPChange) GlobalEventSystem:Bind(GlobalEvents.ExpChanged, MainUIRoleHeadView.UpdateLv, self) end function MainUIRoleHeadView:UpdateLv( ) self.lv_txt.text = MainRole:GetLv() end function MainUIRoleHeadView:UpdateHP( ) local goe = RoleMgr.GetInstance():GetMainRole() local entity = goe.Entity; if not ECS:HasComponent(entity, CS.UnityMMO.Component.HealthStateData) then return end local hpData = ECS:GetComponentData(entity, CS.UnityMMO.Component.HealthStateData) self.blood_bar_img.fillAmount = Mathf.Clamp01(hpData.CurHp/hpData.MaxHp) end function MainUIRoleHeadView:UpdateHead( ) local career = MainRole:GetInstance():GetCareer() local headRes = ResPath.GetRoleHeadRes(career, 0) UI.SetRawImage(self, self.head_icon_raw, headRes) end function MainUIRoleHeadView:UpdateView( ) self:UpdateHead() self:UpdateHP() self:UpdateLv() end return MainUIRoleHeadView
0
0.890903
1
0.890903
game-dev
MEDIA
0.933575
game-dev
0.976365
1
0.976365
pathea-games/planetexplorers
43,673
Assets/Scripts/PuJi/Town/Tool/VArtifactUtil.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Pathea.Maths; using System.IO; using System.Collections; using Mono.Data.SqliteClient; using VANativeCampXML; using VArtifactTownXML; using TownData; using Pathea; public class Town_artifacts { public int ID; public string isoName; public IntVector3 vaSize; public List<BuildingCell> buildingCell; public List<Vector3> npcPos; public Vector3 towerPos; } public struct AllyName{ public int id; public int raceId; public int nameId; } public class BuildingCell { public Vector3 cellPos; public float cellRot; } public class WeightPool { public int maxValue = 0; List<int> weightTree = new List<int>(); List<int> idTree = new List<int>(); public int count = 0; public void Add(int weight, int id) { maxValue += weight; weightTree.Add(maxValue); idTree.Add(id); count++; } public void Clear() { maxValue = 0; weightTree = new List<int>(); idTree = new List<int>(); count = 0; } public int GetRandID(System.Random randSeed) { if (maxValue == 0) { return -1; } int value = randSeed.Next(maxValue); for (int i = 0; i < count; i++) { if (value < weightTree[i]) { return idTree[i]; } } return -1; } public List<int> PickSomeId(System.Random randSeed, int pickAmount) { List<int> pickedId = new List<int>(); List<int> tempWeightTree = new List<int> (weightTree); List<int> tempIdTree = new List<int> (idTree); int tempMax = maxValue; int tempCount =count; for (int i = 0; i < pickAmount; i++) { int value = randSeed.Next(tempMax); for(int j=0;j<tempCount;j++){ if (value < tempWeightTree[j]) { pickedId.Add(tempIdTree[j]); int pickedWeight; if(j==0) pickedWeight = tempWeightTree[0]; else pickedWeight = tempWeightTree[j]-tempWeightTree[j-1]; for(int m = j+1;m<tempCount;m++){ tempWeightTree[m] -= pickedWeight; } tempWeightTree.RemoveAt(j); tempIdTree.RemoveAt(j); tempMax -= pickedWeight; tempCount--; break; } } } return pickedId; } } public struct DynamicNativePoint { public Vector3 point; public int id; public int type;//0 group,1 single } public class VArtifactUtil { public static String ISOPath = ""; public static String GetISONameFullPath(string filenameWithoutExtension) { return ISOPath + "/" + filenameWithoutExtension + ".art"; } public static Dictionary<int, Town_artifacts> townArtifactsData = new Dictionary<int, Town_artifacts>();//load from database public static Dictionary<int,int> townNameData = new Dictionary<int, int>(); public static Dictionary<int,AllyName> allyNameData = new Dictionary<int, AllyName>(); public static Dictionary<string, ulong> isoNameId = new Dictionary<string, ulong>(); public static Dictionary<ulong, VArtifactData> isos = new Dictionary<ulong, VArtifactData>(); public static Dictionary<int, ulong> townIdIso = new Dictionary<int, ulong>(); public static Dictionary<Vector3, int> loadedPos = new Dictionary<Vector3, int>(); public static Dictionary<IntVector3, VFVoxel> artTown = new Dictionary<IntVector3, VFVoxel>(); public static int townCount = 0; //public VArtifactCursor.OnOutputVoxel OutputTownVoxel; public static int spawnRadius0 = 0; public static int spawnRadius = 0; public static string[] triplaner = new string[]{"4,3,68,24,17,23,23,23", "8,6,66,21,22,22,22,66", "14,15,12,13,12,12,13,15", "26,27,65,25,65,25,65,65", "9,5,22,22,17,23,22,24", "8,17,22,66,66,24,23,66", //"32,31,22,22,66,66,23,23", //"7,7,66,66,22,22,23,23", "2,5,18,24,17,18,24,35", "20,59,67,67,20,67,67,67"}; public static int triplanerIndex_grassLand = 0; public static int triplanerIndex_forest = 1; public static int triplanerIndex_dessert = 2; public static int triplanerIndex_redStone = 3; public static int triplanerIndex_rainforest = 4; public static int triplanerIndex_hill = 5; public static int triplanerIndex_swamp = 6; public static int triplanerIndex_crater = 7; public static void Clear() { isoNameId.Clear(); isos.Clear(); townIdIso.Clear(); loadedPos.Clear(); artTown.Clear(); townCount = 0; } public static void OutputTownVoxel(int x, int y, int z, VCVoxel voxel, VArtifactUnit town) { IntVector3 pos = new IntVector3(x, y, z); VFVoxel vfvoxel = new VFVoxel(); vfvoxel.Type = voxel.Type; vfvoxel.Volume = voxel.Volume; if (town.townVoxel.ContainsKey(pos)) { VFVoxel originVoxel = town.townVoxel[pos]; vfvoxel.Volume = (byte)Mathf.Clamp(vfvoxel.Volume + originVoxel.Volume, 0, 255); } town.townVoxel[pos] = vfvoxel; //Debug.LogError("addarttown:"+pos); } //Vector3 xdir = Vector3.right; //Vector3 ydir = Vector3.up; //Vector3 zdir = Vector3.forward; //q.eulerAngles = new Vector3 (0,50,0); //xdir = (q * xdir).normalized; //ydir = (q * ydir).normalized; //zdir = (q * zdir).normalized; //Matrix4x4 mat = new Matrix4x4 (); //mat.SetTRS(p_artifact, q, Vector3.one); //t.position = mat.MultiplyPoint(p0); //Transform t; //t.rotation = q; //public Vector3 Size { get { return ISO.m_HeadInfo.si; } } //public static Vector3 Origin //{ // get { return worldPos; } //} //public static Vector3 XDir //{ // get { return (q * Vector3.right).normalized; } //} //public static Vector3 YDir //{ // get { return (q * Vector3.up).normalized; } //} //public static Vector3 ZDir //{ // get { return (q * Vector3.forward).normalized; } //} //public static Vector3 XDir //{ // get { return Vector3.right; } //} //public static Vector3 YDir //{ // get { return Vector3.up; } //} //public static Vector3 ZDir //{ // get { return Vector3.forward; } //} public VArtifactUtil() { } public static bool LoadIso(string path) { VArtifactData ISO; long tick = System.DateTime.Now.Ticks; try { ISO = new VArtifactData(); string fullpath = path; string filename = Path.GetFileNameWithoutExtension(fullpath); //TextAsset ta = Resources.Load(fullpath,typeof(TextAsset)) as TextAsset; using (FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read)) { byte[] iso_buffer = new byte[(int)(fs.Length)]; //byte[] iso_buffer = ta.bytes; ulong guid = CRC64.Compute(iso_buffer); fs.Read(iso_buffer, 0, (int)(fs.Length)); fs.Close(); if (ISO.Import(iso_buffer, new VAOption(false))) { isos[guid] = ISO; isoNameId[filename] = guid; Debug.Log("loadIso Time: " + (System.DateTime.Now.Ticks - tick)); return true; } else { ISO = null; return false; } } } catch (Exception e) { Debug.LogError("Failed to load file "+path); GameLog.HandleIOException(e, GameLog.EIOFileType.InstallFiles); ISO = null; return false; } } public static VArtifactData GetIsoData(string isoName, out ulong guid) { guid = GetGuidFromIsoName(isoName); if (guid == 0) { Debug.LogError("isoName not exist!"); return null; } if (!isos.ContainsKey(guid)) { LoadIso(GetISONameFullPath(isoName)); } VArtifactData isoData = isos[guid]; return isoData; } public static void ClearAllISO() { isos.Clear(); } public static void ClearISO(string filename) { isos.Remove(isoNameId[filename]); } public static void ClearISO(ulong isoGuId) { isos.Remove(isoGuId); } //public static void OutputVoxels(Vector3 worldPos, ulong guid, VArtifactTown newTown) //{ // ISO = isos[guid]; // OutputVoxels(worldPos,newTown); //} //public static void OutputVoxels(Vector3 worldPos, int townId, VArtifactTown newTown) //{ // ulong guid = townIdIso[townId]; // ISO = isos[guid]; // OutputVoxels(worldPos,newTown); //} public static void OutputVoxels(Vector3 worldPos, VArtifactUnit newTown, float rotation = 0) { if (!isos.ContainsKey(newTown.isoGuId)) LoadIso(GetISONameFullPath(newTown.isoName)); if (!isos.ContainsKey(newTown.isoGuId)) { Debug.LogError("isoGuId error: " + newTown.isoGuId + "isoName: " + newTown.isoName); return; } VArtifactData isoData = isos[newTown.isoGuId]; //long tick = System.DateTime.Now.Ticks; Quaternion q = new Quaternion(); q.eulerAngles = new Vector3(0, rotation, 0); Vector3 XDir = (q * Vector3.right).normalized; Vector3 YDir = (q * Vector3.up).normalized; Vector3 ZDir = (q * Vector3.forward).normalized; //Vector3 XDir = Vector3.right; //Vector3 YDir = Vector3.up; //Vector3 ZDir = Vector3.forward; Vector3 ofs = new Vector3(isoData.m_HeadInfo.xSize, 0, isoData.m_HeadInfo.zSize) * (-0.5f); Vector3 new_pos = worldPos + q * ofs; foreach (KeyValuePair<int, VCVoxel> kvp in isoData.m_Voxels) { Vector3 lpos = new Vector3(kvp.Key & 0x3ff, kvp.Key >> 20, (kvp.Key >> 10) & 0x3ff); Vector3 wpos = new_pos + lpos.x * XDir + lpos.y * YDir + lpos.z * ZDir; INTVECTOR3 wpos_floor = new INTVECTOR3(Mathf.FloorToInt(wpos.x), Mathf.FloorToInt(wpos.y), Mathf.FloorToInt(wpos.z)); INTVECTOR3 wpos_ceil = new INTVECTOR3(Mathf.CeilToInt(wpos.x), Mathf.CeilToInt(wpos.y), Mathf.CeilToInt(wpos.z)); if (wpos_floor == wpos_ceil) { OutputTownVoxel(wpos_floor.x, wpos_floor.y, wpos_floor.z, kvp.Value, newTown); } else { for (int x = wpos_floor.x; x <= wpos_ceil.x; ++x) { for (int y = wpos_floor.y; y <= wpos_ceil.y; ++y) { for (int z = wpos_floor.z; z <= wpos_ceil.z; ++z) { float deltax = 1 - Mathf.Abs(wpos.x - x); float deltay = 1 - Mathf.Abs(wpos.y - y); float deltaz = 1 - Mathf.Abs(wpos.z - z); float u = deltax * deltay * deltaz; if (u < 0.5f) u = u / (0.5f + u); else u = 0.5f / (1.5f - u); VCVoxel voxel = kvp.Value; voxel.Volume = (byte)Mathf.CeilToInt(voxel.Volume * u); if (voxel.Volume > 1) OutputTownVoxel(x, y, z, voxel, newTown); } } } } } // Debug.LogError("Output Time: " + (System.DateTime.Now.Ticks - tick) + " townCount:" + (++townCount)); } public static List<IntVector2> OccupiedTile(List<VArtifactUnit> artifactList) { List<IntVector2> OccupiedTileList = new List<IntVector2>(); for (int i = 0; i < artifactList.Count; i++) { List<IntVector2> aList = LinkedChunkIndex(artifactList[i]); for (int j = 0; j < aList.Count; j++) { if (!OccupiedTileList.Contains(aList[j])) { OccupiedTileList.Add(aList[j]); } } } return OccupiedTileList; } public static List<IntVector2> LinkedChunkIndex(VArtifactUnit townInfo) { IntVector2 startPos = townInfo.PosStart; IntVector2 endPos = townInfo.PosEnd; List<IntVector2> startIndexList = Link1PointToChunk(startPos); List<IntVector2> endIndexList = Link1PointToChunk(endPos); IntVector2 startIndex = GetMinChunkIndex(startIndexList); IntVector2 endIndex = GetMaxChunkIndex(endIndexList); List<IntVector2> chunkIndexList = GetChunkIndexListFromStartEnd(startIndex, endIndex); return chunkIndexList; } public static List<IntVector2> GetChunkIndexListFromStartEnd(IntVector2 startIndex, IntVector2 endIndex) { List<IntVector2> ChunkIndexList = new List<IntVector2>(); for (int x = startIndex.x; x <= endIndex.x; x++) { for (int z = startIndex.y; z <= endIndex.y; z++) { IntVector2 index = new IntVector2(x, z); if (!ChunkIndexList.Contains(index)) ChunkIndexList.Add(index); } } return ChunkIndexList; } public static IntVector2 GetMinChunkIndex(List<IntVector2> startIndexList) { if (startIndexList == null || startIndexList.Count <= 0) return null; IntVector2 minIndex = new IntVector2(); minIndex = startIndexList[0]; for (int i = 0; i < startIndexList.Count; i++) { if (startIndexList[i].x <= minIndex.x && startIndexList[i].y <= minIndex.y) minIndex = startIndexList[i]; } return minIndex; } public static IntVector2 GetMaxChunkIndex(List<IntVector2> endIndexList) { if (endIndexList == null || endIndexList.Count <= 0) return null; IntVector2 maxIndex = new IntVector2(); maxIndex = endIndexList[0]; for (int i = 0; i < endIndexList.Count; i++) { if (endIndexList[i].x >= maxIndex.x && endIndexList[i].y >= maxIndex.y) maxIndex = endIndexList[i]; } return maxIndex; } public static List<IntVector2> Link1PointToChunk(IntVector2 pos) { List<IntVector2> indexList = new List<IntVector2>(); int i = pos.x; int j = pos.y; int x = i >> VoxelTerrainConstants._shift; int z = j >> VoxelTerrainConstants._shift; IntVector2 chunkIndexXZ = new IntVector2(x, z); indexList.Add(chunkIndexXZ); int x2 = x; if ((i + VoxelTerrainConstants._numVoxelsPrefix) % VoxelTerrainConstants._numVoxelsPerAxis == 0) { x2 = (i + VoxelTerrainConstants._numVoxelsPrefix) >> VoxelTerrainConstants._shift; } else if (i % VoxelTerrainConstants._numVoxelsPerAxis < VoxelTerrainConstants._numVoxelsPostfix) { x2 = (i - 2) >> VoxelTerrainConstants._shift; } int z2 = z; if ((j + VoxelTerrainConstants._numVoxelsPrefix) % VoxelTerrainConstants._numVoxelsPerAxis == 0) { z2 = (j + VoxelTerrainConstants._numVoxelsPrefix) >> VoxelTerrainConstants._shift; } else if (j % VoxelTerrainConstants._numVoxelsPerAxis < VoxelTerrainConstants._numVoxelsPostfix) { z2 = (j - VoxelTerrainConstants._numVoxelsPostfix) >> VoxelTerrainConstants._shift; } if (x2 != x && z2 == z) { chunkIndexXZ = new IntVector2(x2, z); if (!indexList.Contains(chunkIndexXZ)) { indexList.Add(chunkIndexXZ); } } else if (x2 == x && z2 != z) { chunkIndexXZ = new IntVector2(x, z2); if (!indexList.Contains(chunkIndexXZ)) { indexList.Add(chunkIndexXZ); } } else if (x2 != x && z2 != z) { chunkIndexXZ = new IntVector2(x2, z); if (!indexList.Contains(chunkIndexXZ)) { indexList.Add(chunkIndexXZ); } chunkIndexXZ = new IntVector2(x, z2); if (!indexList.Contains(chunkIndexXZ)) { indexList.Add(chunkIndexXZ); } chunkIndexXZ = new IntVector2(x2, z2); if (!indexList.Contains(chunkIndexXZ)) { indexList.Add(chunkIndexXZ); } } return indexList; } public static VArtifactData GetVartifactDataFromIsoName(string isoName) { if (isoNameId.ContainsKey(isoName)) { ulong guid = isoNameId[isoName]; if (isos.ContainsKey(guid)) { return isos[guid]; } } return null; } public static ulong GetGuidFromIsoName(string isoName) { if (isoNameId.ContainsKey(isoName)) { return isoNameId[isoName]; } return 0; } //to judge whether a posXZ is in a town public static float IsInTown(IntVector2 posXZ) { if (VArtifactTownManager.Instance == null) { return 0; } int chunkX = posXZ.x >> VoxelTerrainConstants._shift; int chunkZ = posXZ.y >> VoxelTerrainConstants._shift; IntVector2 chunkPos = new IntVector2(chunkX, chunkZ); //if (!VArtifactTownManager.Instance.TownChunk.ContainsKey(chunkPos)) //{ // return null; //} //IntVector2 townCenter = VArtifactTownManager.Instance.TownChunk[chunkPos]; if (!VArtifactTownManager.Instance.IsTownChunk(chunkPos)) { return 0; } float townHeight = VArtifactTownManager.Instance.GetTownCenterByTileAndPos(chunkPos, posXZ); return townHeight; } public static bool IsInTown(IntVector2 posXZ,out IntVector2 townPosCenter){ townPosCenter = new IntVector2(-9999999,-9999999); if (VArtifactTownManager.Instance == null) { return false; } if(VArtifactTownManager.Instance==null) return false; foreach(VArtifactTown vat in VArtifactTownManager.Instance.townPosInfo.Values){ if(vat.isEmpty) continue; if(IntVector2.SqrMagnitude(posXZ-vat.PosCenter)<=vat.radius*vat.radius){ townPosCenter = vat.PosCenter; return true; } } return false; } public static VArtifactTown GetPosTown(Vector3 pos) { IntVector2 posXZ = new IntVector2(Mathf.RoundToInt(pos.x), Mathf.RoundToInt(pos.z)); int chunkX = posXZ.x >> VoxelTerrainConstants._shift; int chunkZ = posXZ.y >> VoxelTerrainConstants._shift; IntVector2 chunkPos = new IntVector2(chunkX, chunkZ); if (VArtifactTownManager.Instance==null||!VArtifactTownManager.Instance.IsTownChunk(chunkPos)) { return null; } return VArtifactTownManager.Instance.GetTileTown(chunkPos); } public static bool CheckTownAvailable(VArtifactTown vaTowndata) { if (!IsContained(vaTowndata)){ for (int i = 0; i < vaTowndata.VAUnits.Count; i++) { VArtifactUnit vau = vaTowndata.VAUnits[i]; vau.worldPos = new Vector3(vau.PosCenter.x, -1, vau.PosCenter.y); } return true; } return false; } public static void GetArtifactUnit(VArtifactTown townData, ArtifactUnit[] artifactUnitArray, System.Random myRand) { int townPosXMin = townData.PosGen.x; int townPosZMin = townData.PosGen.y; int townPosXMax = townData.PosGen.x; int townPosZMax = townData.PosGen.y; int unitIndex = 0; for (int m = 0; m < artifactUnitArray.Count(); m++) { IntVector2 posXZ = VArtifactUtil.GetIntVector2FromStr(artifactUnitArray[m].pos); int unitID; if (artifactUnitArray[m].id.Equals("-1")) { List<int> idList = VArtifactUtil.townArtifactsData.Keys.ToList(); unitID = idList[myRand.Next(idList.Count)]; } else { unitID = VArtifactUtil.RandIntFromStr(artifactUnitArray[m].id, myRand); } //Debug.Log("unitID:" + unitID); Town_artifacts townDataFromDataBase = VArtifactUtil.townArtifactsData[unitID]; string isoName = townDataFromDataBase.isoName; float rot; if (artifactUnitArray[m].rot.Equals("-1")) { //--to do: "type" is not used rot = (float)(myRand.NextDouble() * 360); } else { rot = VArtifactUtil.RandFloatFromStr(artifactUnitArray[m].rot, myRand); } //--to do: get the isoData from id; ulong guid; //townData.isodataList.Add(posXZ,GetIsoData(isoName,out guid)); VArtifactUnit vau = new VArtifactUnit(); VArtifactData isoData = VArtifactUtil.GetIsoData(isoName, out guid); if (isoData == null) { Debug.LogError("unitID:" + unitID + " isoName not found! IsoName: " + isoName); continue; } vau.isoName = isoName; vau.unitIndex = unitIndex++; vau.isoId = unitID; vau.isoGuId = guid; vau.vat = townData; vau.rot = rot; vau.PosCenter = posXZ + townData.PosGen; int xIsoSize = isoData.m_HeadInfo.xSize; int zIsoSize = isoData.m_HeadInfo.zSize; vau.isoStartPos = new IntVector2(posXZ.x - xIsoSize / 2, posXZ.y - zIsoSize / 2) + townData.PosGen; vau.isoEndPos = new IntVector2(posXZ.x + xIsoSize / 2, posXZ.y + zIsoSize / 2) + townData.PosGen; int xSize = townDataFromDataBase.vaSize.x; int zSize = townDataFromDataBase.vaSize.y; vau.PosStart = new IntVector2(posXZ.x - xSize / 2, posXZ.y - zSize / 2) + townData.PosGen; vau.PosEnd = new IntVector2(posXZ.x + xSize / 2, posXZ.y + zSize / 2) + townData.PosGen; vau.level = townData.level; vau.type = townData.type; vau.buildingIdNum = artifactUnitArray[m].buildingIdNum.ToList(); vau.npcIdNum = artifactUnitArray[m].npcIdNum.ToList(); vau.buildingCell = townDataFromDataBase.buildingCell; vau.npcPos = townDataFromDataBase.npcPos; vau.vaSize = townDataFromDataBase.vaSize; vau.towerPos = townDataFromDataBase.towerPos; if (vau.PosStart.x < townPosXMin) townPosXMin = vau.PosStart.x; if (vau.PosStart.y < townPosZMin) townPosZMin = vau.PosStart.y; if (vau.PosEnd.x > townPosXMax) townPosXMax = vau.PosEnd.x; if (vau.PosEnd.y > townPosZMax) townPosZMax = vau.PosEnd.y; townData.VAUnits.Add(vau); } townData.PosStart = new IntVector2(townPosXMin, townPosZMin); townData.PosEnd = new IntVector2(townPosXMax, townPosZMax); townData.PosCenter = new IntVector2((townPosXMin + townPosXMax) / 2, (townPosZMin + townPosZMax) / 2); // townData.height = Mathf.CeilToInt(townData.VAUnits[0].worldPos.y + townData.VAUnits[0].vaSize.z); // townData.TransPos = new Vector3(townData.PosCenter.x, townData.height, townData.PosCenter.y); townData.radius = (int)Mathf.Sqrt(Mathf.Pow((townPosXMax - townPosXMin) / 2, 2) + Mathf.Pow((townPosZMax - townPosZMin) / 2, 2)); } public static Vector3 GetPosAfterRotation(VArtifactUnit vau, Vector3 relativePos) { Quaternion q = new Quaternion(); q.eulerAngles = new Vector3(0, vau.rot, 0); Vector3 ofs = relativePos - vau.worldPos; ofs.x += vau.isoStartPos.x; ofs.y += vau.worldPos.y; ofs.z += vau.isoStartPos.y; Vector3 rezultPos = vau.worldPos + q * ofs; return rezultPos; } public static DynamicNativePoint GetDynamicNativePoint(int townId) { VArtifactTown vat = VArtifactTownManager.Instance.GetTownByID(townId); DynamicNativePoint result; DynamicNative[] dns = vat.nativeTower.dynamicNatives; System.Random randSeed = new System.Random(System.DateTime.Now.Millisecond); DynamicNative dn = dns[randSeed.Next(dns.Count())]; result.id = dn.did; result.type = dn.type; if (dn.type == 1) { result.point = GetDynamicNativeSinglePoint(vat, randSeed); } else { result.point = GetDynamicNativeGroupPoint(vat, randSeed); } return result; } public static Vector3 GetDynamicNativeSinglePoint(VArtifactTown vat, System.Random randSeed) { VArtifactUnit vau = vat.VAUnits[randSeed.Next(vat.VAUnits.Count)]; Vector3 posBeforRot = vau.npcPos[randSeed.Next(vau.npcPos.Count)]; return GetPosAfterRotation(vau, posBeforRot); } public static Vector3 GetDynamicNativeGroupPoint(VArtifactTown vat, System.Random randSeed) { return GetDynamicNativeSinglePoint(vat, randSeed); } public static DynamicNative[] GetAllDynamicNativePoint(int townId,out List<Vector3> posList){ DynamicNative[] result =null; posList = new List<Vector3> (); if(VArtifactTownManager.Instance!=null){ VArtifactTown vat = VArtifactTownManager.Instance.GetTownByID(townId); if(vat!=null){ if(vat.nativeTower!=null){ result = vat.nativeTower.dynamicNatives; if(vat.VAUnits!=null&&vat.VAUnits.Count>0){ VArtifactUnit vau = vat.VAUnits[0]; List<Vector3> posBeforRot= vau.npcPos; foreach(Vector3 p in posBeforRot){ posList.Add(GetPosAfterRotation(vau, p)); } }else{ Debug.LogError("GetAllDynamicNativePoint: "+"vat.VAUnits==null||vat.VAUnits.Count=0"); } }else{ Debug.LogError("GetAllDynamicNativePoint: "+"vat.nativeTower==null"); } }else{ Debug.LogError("GetAllDynamicNativePoint: "+"vat==null"); } }else{ Debug.LogError("GetAllDynamicNativePoint: "+"ArtifactTownManager.Instance==null"); } return result; } public static void LoadData() { LoadTownArtifact(); LoadTownNameData(); LoadAllyName(); } public static void LoadTownArtifact(){ SqliteDataReader reader = LocalDatabase.Instance.ReadFullTable("Town_artifacts"); while (reader.Read()) { Town_artifacts townArtifact = new Town_artifacts(); townArtifact.ID = Convert.ToInt32(reader.GetString(reader.GetOrdinal("Id"))); townArtifact.isoName = reader.GetString(reader.GetOrdinal("Name")); townArtifact.vaSize = GetIntVector3FromStr(reader.GetString(reader.GetOrdinal("Size"))); string b_positions = reader.GetString(reader.GetOrdinal("B_position")); string npc_borns = reader.GetString(reader.GetOrdinal("NPC_born")); string tower_pos = reader.GetString(reader.GetOrdinal("Tower")); townArtifact.buildingCell = new List<BuildingCell>(); string[] buildingCellStr = b_positions.Split('_'); for (int i = 0; i < buildingCellStr.Count(); i++) { BuildingCell bc = new BuildingCell(); string[] posRotStr = buildingCellStr[i].Split(';'); bc.cellPos = GetVector3FromStr(posRotStr[0]); bc.cellRot = float.Parse(posRotStr[1]); townArtifact.buildingCell.Add(bc); } townArtifact.npcPos = new List<Vector3>(); string[] npcPosStr = npc_borns.Split('_'); for (int i = 0; i < npcPosStr.Count(); i++) { Vector3 npcPos = GetVector3FromStr(npcPosStr[i]); townArtifact.npcPos.Add(npcPos); } townArtifact.towerPos = GetVector3FromStr(tower_pos); townArtifactsData.Add(townArtifact.ID, townArtifact); } } public static void LoadTownNameData(){ SqliteDataReader reader = LocalDatabase.Instance.ReadFullTable("TownName"); while (reader.Read()) { int id = Convert.ToInt32(reader.GetString(reader.GetOrdinal("Id"))); int nameId = Convert.ToInt32(reader.GetString(reader.GetOrdinal("TranslationId"))); townNameData.Add(id,nameId); } } public static int GetTownNameId(int id){ if(townNameData.ContainsKey(id)) return townNameData[id]; return -1; } public static void LoadAllyName(){ SqliteDataReader reader = LocalDatabase.Instance.ReadFullTable("AdvCampName"); while (reader.Read()) { AllyName an = new AllyName (); an.id = Convert.ToInt32(reader.GetString(reader.GetOrdinal("ID"))); an.raceId = Convert.ToInt32(reader.GetString(reader.GetOrdinal("Race"))); an.nameId = Convert.ToInt32(reader.GetString(reader.GetOrdinal("TranslationID"))); allyNameData.Add(an.id,an); } } public static bool IsContained(VArtifactTown townInfo) { for (int vaui = 0; vaui < townInfo.VAUnits.Count; vaui++) { List<IntVector2> chunkIndexList = LinkedChunkIndex(townInfo.VAUnits[vaui]); for (int i = 0; i < chunkIndexList.Count; i++) { IntVector2 chunkIndex = chunkIndexList[i]; if (VArtifactTownManager.Instance.TileContainsTown(chunkIndex)) { return true; } } } return false; } public static Vector3 GetStartPos() { if(PeGameMgr.IsSingleAdventure) return VArtifactTownManager.Instance.playerStartPos; IntVector2 posXZ = GetSpawnPos(); Vector3 pos = new Vector3(posXZ.x, VFDataRTGen.GetPosTop(posXZ), posXZ.y); return pos; } public static IntVector2 GetSpawnPos() { System.Random seed = new System.Random(System.DateTime.Now.Millisecond); if (PeGameMgr.IsMultiAdventure) { if (PeGameMgr.IsMultiCoop) { return new IntVector2(Mathf.RoundToInt(VArtifactTownManager.Instance.playerStartPos.x),Mathf.RoundToInt(VArtifactTownManager.Instance.playerStartPos.z)); // List<VArtifactTown> townList = VATownGenerator.Instance.GetAllyTowns(TownGenData.PlayerAlly); // townList= townList.FindAll (it=>it.townId==0); // if (townList.Count==0) // { // LogManager.Error("No town! "); // return VATownGenerator.Instance.GetInitPos(seed); // } // // int count = seed.Next(townList.Count); // return townList[count].PosCenter; } else if (PeGameMgr.IsMultiVS) { List<VArtifactTown> townList = VATownGenerator.Instance.GetAllyTowns(TownGenData.PlayerAlly); townList= townList.FindAll (it=>it.level<=1&&it.isMainTown); if (townList.Count==0) { LogManager.Error("No town! "); return VATownGenerator.Instance.GetInitPos(seed); } int townCount = townList.Count; List<int> indexGroup = new List<int>(); for (int i = 0; i < townCount; i++) { indexGroup.Add(i); } Shuffle(indexGroup, new System.Random(RandomMapConfig.RandSeed)); int townIndex = indexGroup[BaseNetwork.MainPlayer.TeamId % townCount]; VArtifactTown townInfo = townList[townIndex]; IntVector2 townCenter = townInfo.PosCenter; IntVector2 spawnPos = new IntVector2(townCenter.x + seed.Next(-spawnRadius, spawnRadius), townCenter.y + seed.Next(-spawnRadius, spawnRadius)); return spawnPos; } else //GameConfig.IsMultiSurvive { List<VArtifactTown> townList = VATownGenerator.Instance.GetAllyTowns(TownGenData.PlayerAlly); townList= townList.FindAll (it=>it.level<=1&&it.isMainTown); if (townList.Count==0) { LogManager.Error("No town! "); return VATownGenerator.Instance.GetInitPos(seed); } int count = seed.Next(townList.Count); VArtifactTown townInfo = townList[count]; IntVector2 townCenter = townInfo.PosCenter; IntVector2 spawnPos = new IntVector2(townCenter.x + seed.Next(-spawnRadius, spawnRadius), townCenter.y + seed.Next(-spawnRadius, spawnRadius)); return spawnPos; } } else { IntVector2 spawnPos = VATownGenerator.Instance.GetInitPos(); return spawnPos; } } public static void SetNpcStandRot(PeEntity npc,float rot,bool isStand) { if (npc == null) return; NpcCmpt npcCmpt = npc.GetCmpt<NpcCmpt>(); if (npcCmpt != null) { npcCmpt.Req_Rotation(Quaternion.Euler(0,rot,0)); npcCmpt.StandRotate = rot; // if(isStand) // npcCmpt.Req_SetIdle("Idle"); } } public static void GetPosRotFromPointRot(ref Vector3 pos, ref float rot, Vector3 refPos, float refRot) { Quaternion q = new Quaternion(); q.eulerAngles = new Vector3(0, refRot, 0); pos = refPos + q * pos; rot = refRot + rot; } //public static bool IsInBuildingArea(Vector2 pos, List<VArtifactUnit> vauList) //{ // bool flag = false; // foreach(VArtifactUnit vau in vauList) // { // foreach (BuildingID bid in vau.buildingPosID.Values) // { // Quaternion q = new Quaternion(); // q.eulerAngles = new Vector3(0, -vab.rotation, 0); // Vector3 pointPos = new Vector3(pos.x, vab.root.y, pos.y); // Vector3 relativePos = q * (pointPos - vab.root); // if (relativePos.x > -vab.size.x / 2 && relativePos.x < vab.size.x / 2 // && relativePos.z > -vab.size.y && relativePos.z < vab.size.y / 2) // { // flag = true; // break; // } // } // if (flag) // break; // } // return flag; //} #region Town public static void ShowAllTowns(){ List<VArtifactTown> vatList = VArtifactTownManager.Instance.townPosInfo.Values.ToList(); foreach(VArtifactTown vat in vatList){ if(vat.Type==VArtifactType.NpcTown) RandomMapIconMgr.AddTownIcon(vat); else RandomMapIconMgr.AddNativeIcon(vat); } } public static void RemoveAllTowns(){ RandomMapIconMgr.ClearAll(); } public static bool HasTown(){ if(VArtifactTownManager.Instance==null) return false; return VArtifactTownManager.Instance.townPosInfo.Values.Count>0; } public static float GetNearestTownDistance(int x,int z,out VArtifactTown vaTown){ float distancePow = float.MaxValue; vaTown= null; if(VArtifactTownManager.Instance==null) return distancePow; foreach(VArtifactTown vat in VArtifactTownManager.Instance.townPosInfo.Values){ if(vat.isEmpty) continue; float d = (vat.PosCenter.x-x)*(vat.PosCenter.x-x)+(vat.PosCenter.y-z)*(vat.PosCenter.y-z); if(d<distancePow){ distancePow = d; vaTown = vat; } } return Mathf.Sqrt(distancePow); } public static bool IsInTownBallArea(Vector3 pos){ if(VArtifactTownManager.Instance==null) return false; foreach(VArtifactTown vat in VArtifactTownManager.Instance.townPosInfo.Values){ if(vat.isEmpty) continue; if((pos-vat.TransPos).sqrMagnitude<=vat.radius*vat.radius) return true; } return false; } //-1:none,0:puja,1:paja public static int IsInNativeCampArea(Vector3 pos){ if(VArtifactTownManager.Instance==null){ return -1; } IntVector2 posXZ = new IntVector2 (Mathf.RoundToInt(pos.x),Mathf.RoundToInt(pos.z)); IntVector2 tileIndex = new IntVector2 (posXZ.x>>VoxelTerrainConstants._shift,posXZ.y>>VoxelTerrainConstants._shift); VArtifactTown vat =VArtifactTownManager.Instance.GetTileTown(tileIndex); if(vat==null) return -1; else if(vat.type==VArtifactType.NativeCamp){ if(vat.PosCenter.Distance(posXZ)<vat.radius&&vat.InYArea(pos.y)){ if(vat.nativeType==NativeType.Puja){ return 0; } else{ return 1; } }else return -1; }else return -1; } public static void ChangeTownAlliance(int townId){ VArtifactTown vat = VArtifactTownManager.Instance.GetTownByID(townId); if(vat!=null) VATownGenerator.Instance.ChangeAlliance(vat); //--to do: refresh } public static void RestoreTownAlliance(int townId){ VArtifactTown vat = VArtifactTownManager.Instance.GetTownByID(townId); if(vat!=null) VATownGenerator.Instance.RestoreAlliance(vat); //--to do: refresh } public static bool GetTownPos(int townId,out Vector3 pos){ if(VArtifactTownManager.Instance==null){ pos=Vector3.zero; return false; } else{ VArtifactTown vat = VArtifactTownManager.Instance.GetTownByID(townId); if(vat==null) { pos = Vector3.zero; return false; }else{ pos = vat.TransPos; return true; } } } public static bool GetTownName(int townId,out string name){ if(VArtifactTownManager.Instance==null){ name=""; return false; } else{ VArtifactTown vat = VArtifactTownManager.Instance.GetTownByID(townId); if(vat==null) { name = ""; return false; }else{ name = PELocalization.GetString(vat.townNameId); return true; } } } public static int GetFirstEnemyNpcColor(){ if(VATownGenerator.Instance==null) return -1; return VATownGenerator.Instance.GetFirstEnemyNpcAllyColor(); } public static int GetFirstEnemyNpcPlayerId(){ if(VATownGenerator.Instance==null) return -1; return VATownGenerator.Instance.GetFirstEnemyNpcAllyPlayerId(); } public static void RegistTownDestryedEvent(VArtifactTownManager.TownDestroyed eventListener){ if(VArtifactTownManager.Instance!=null){ VArtifactTownManager.Instance.TownDestroyedEvent-=eventListener; VArtifactTownManager.Instance.TownDestroyedEvent+=eventListener; } } public static void UnRegistTownDestryedEvent(VArtifactTownManager.TownDestroyed eventListener){ if(VArtifactTownManager.Instance!=null){ VArtifactTownManager.Instance.TownDestroyedEvent-=eventListener; } } #endregion #region tool public static void Shuffle(List<int> id, System.Random myRand) { int size = id.Count; List<int> temp = new List<int>(); for (int i = 0; i < size; i++) { temp.Add(id[i]); } int index = 0; while (temp.Count > 0) { int i = myRand.Next(temp.Count); id[index] = temp[i]; index++; temp.RemoveAt(i); } } public static List<int> RandomChoose(int num, int minValue, int maxValue, System.Random randomSeed) { List<int> pool = new List<int>(); for (int i = minValue; i < maxValue + 1; i++) { pool.Add(i); } List<int> rezult = new List<int>(); for (int i = 0; i < num; i++) { int index = randomSeed.Next(maxValue - minValue + 1 - i); rezult.Add(pool[index]); pool.RemoveAt(index); } return rezult; } public static Vector3 GetVector3FromStr(string value) { if (value == "0") { return Vector3.zero; } string[] values = value.Split(','); float x = float.Parse(values[0]); float y = float.Parse(values[1]); float z = float.Parse(values[2]); return new Vector3(x, y, z); } public static IntVector2 GetIntVector2FromStr(string value) { string[] values = value.Split(','); int x = Convert.ToInt32(values[0]); int z = Convert.ToInt32(values[1]); return new IntVector2(x, z); } public static IntVector3 GetIntVector3FromStr(string value) { string[] values = value.Split(','); int x = Convert.ToInt32(values[0]); int y = Convert.ToInt32(values[1]); int z = Convert.ToInt32(values[2]); return new IntVector3(x, y, z); } public static int RandIntFromStr(string value, System.Random rand) { string[] values = value.Split(','); int result = rand.Next(values.Count()); result = Convert.ToInt32(values[result]); return result; } public static float RandFloatFromStr(string value, System.Random rand) { string[] values = value.Split(','); int resultIndex = rand.Next(values.Count()); float result = float.Parse(values[resultIndex]); return result; } public static IntVector2 GenCampByZone(IntVector2 center, int zoneNo, int distanceMin, int distanceMax, System.Random randomSeed) { IntVector2 result = new IntVector2(center.x, center.y); switch (zoneNo) { case 0: result.x += randomSeed.Next(-distanceMin / 2, distanceMin / 2); result.y += randomSeed.Next(distanceMin, distanceMax); break; case 1: result.x += randomSeed.Next(distanceMin, distanceMax); result.y += randomSeed.Next(distanceMin, distanceMax); break; case 2: result.x += randomSeed.Next(distanceMin, distanceMax); result.y += randomSeed.Next(-distanceMin / 2, distanceMin / 2); break; case 3: result.x += randomSeed.Next(distanceMin, distanceMax); result.y -= randomSeed.Next(distanceMin, distanceMax); break; case 4: result.x += randomSeed.Next(-distanceMin / 2, distanceMin / 2); result.y -= randomSeed.Next(distanceMin, distanceMax); break; case 5: result.x -= randomSeed.Next(distanceMin, distanceMax); result.y -= randomSeed.Next(distanceMin, distanceMax); break; case 6: result.x -= randomSeed.Next(distanceMin, distanceMax); result.y += randomSeed.Next(-distanceMin / 2, distanceMin / 2); break; case 7: result.x -= randomSeed.Next(distanceMin, distanceMax); result.y += randomSeed.Next(distanceMin, distanceMax); break; default: result.x += randomSeed.Next(distanceMin, distanceMax); result.y += randomSeed.Next(distanceMin, distanceMax); break; } return result; } public static IntVector2 GetRandomPointFromPoint(IntVector2 centerPoint,float MaxRadius, System.Random rand){ IntVector2 resultPoint = null; double dist = rand.NextDouble()*MaxRadius*4/5+MaxRadius/5; double angle = 2*Mathf.PI*rand.NextDouble(); int xDist = Mathf.RoundToInt((float)(dist*Math.Cos(angle))); int zDist = Mathf.RoundToInt((float)(dist*Math.Sin(angle))); resultPoint = new IntVector2(centerPoint.x+xDist,centerPoint.y+zDist); return resultPoint; } #endregion }
0
0.791123
1
0.791123
game-dev
MEDIA
0.725167
game-dev
0.960876
1
0.960876
revolucas/CoC-Xray
27,370
src/xrGame/GamePersistent.cpp
#include "pch_script.h" #include "gamepersistent.h" #include "../xrEngine/fmesh.h" #include "../xrEngine/xr_ioconsole.h" #include "../xrEngine/gamemtllib.h" #include "../Include/xrRender/Kinematics.h" #include "profiler.h" #include "MainMenu.h" #include "UICursor.h" #include "game_base_space.h" #include "level.h" #include "ParticlesObject.h" #include "game_base_space.h" #include "stalker_animation_data_storage.h" #include "stalker_velocity_holder.h" #include "ActorEffector.h" #include "actor.h" #include "UI/UItextureMaster.h" #include "../xrEngine/xrSASH.h" #include "ai_space.h" #include "../xrServerEntities/script_engine.h" #include "holder_custom.h" #include "game_cl_base.h" #include "xrserver_objects_alife_monsters.h" #include "../xrServerEntities/xrServer_Object_Base.h" #include "UI/UIGameTutorial.h" #ifndef MASTER_GOLD # include "custommonster.h" #endif // MASTER_GOLD #ifndef _EDITOR # include "ai_debug.h" #endif // _EDITOR #include "gametype_chooser.h" //#ifdef DEBUG_MEMORY_MANAGER // static void * ode_alloc (size_t size) { return Memory.mem_alloc(size,"ODE"); } // static void * ode_realloc (void *ptr, size_t oldsize, size_t newsize) { return Memory.mem_realloc(ptr,newsize,"ODE"); } // static void ode_free (void *ptr, size_t size) { return xr_free(ptr); } //#else // DEBUG_MEMORY_MANAGER // static void * ode_alloc (size_t size) { return xr_malloc(size); } // static void * ode_realloc (void *ptr, size_t oldsize, size_t newsize) { return xr_realloc(ptr,newsize); } // static void ode_free (void *ptr, size_t size) { return xr_free(ptr); } //#endif // DEBUG_MEMORY_MANAGER CGamePersistent::CGamePersistent(void) { m_bPickableDOF = false; m_game_params.m_e_game_type = eGameIDNoGame; ambient_effect_next_time = 0; ambient_effect_stop_time = 0; ambient_particles = 0; ambient_effect_wind_start = 0.f; ambient_effect_wind_in_time = 0.f; ambient_effect_wind_end = 0.f; ambient_effect_wind_out_time = 0.f; ambient_effect_wind_on = false; ZeroMemory(ambient_sound_next_time, sizeof(ambient_sound_next_time)); m_pUI_core = NULL; m_pMainMenu = NULL; m_intro = NULL; m_intro_event.bind(this, &CGamePersistent::start_logo_intro); #ifdef DEBUG m_frame_counter = 0; m_last_stats_frame = u32(-2); #endif // //dSetAllocHandler (ode_alloc ); //dSetReallocHandler (ode_realloc ); //dSetFreeHandler (ode_free ); // BOOL bDemoMode = (0 != strstr(Core.Params, "-demomode ")); if (bDemoMode) { string256 fname; LPCSTR name = strstr(Core.Params, "-demomode ") + 10; sscanf(name, "%s", fname); R_ASSERT2(fname[0], "Missing filename for 'demomode'"); Msg("- playing in demo mode '%s'", fname); pDemoFile = FS.r_open(fname); Device.seqFrame.Add(this); eDemoStart = Engine.Event.Handler_Attach("GAME:demo", this); uTime2Change = 0; } else { pDemoFile = NULL; eDemoStart = NULL; } eQuickLoad = Engine.Event.Handler_Attach("Game:QuickLoad", this); Fvector3* DofValue = Console->GetFVectorPtr("r2_dof"); SetBaseDof(*DofValue); } CGamePersistent::~CGamePersistent(void) { FS.r_close(pDemoFile); Device.seqFrame.Remove(this); Engine.Event.Handler_Detach(eDemoStart, this); Engine.Event.Handler_Detach(eQuickLoad, this); } void CGamePersistent::RegisterModel(IRenderVisual* V) { // Check types switch (V->getType()) { case MT_SKELETON_ANIM: case MT_SKELETON_RIGID:{ u16 def_idx = GMLib.GetMaterialIdx("default_object"); R_ASSERT2(GMLib.GetMaterialByIdx(def_idx)->Flags.is(SGameMtl::flDynamic), "'default_object' - must be dynamic"); IKinematics* K = smart_cast<IKinematics*>(V); VERIFY(K); int cnt = K->LL_BoneCount(); for (u16 k = 0; k < cnt; k++) { CBoneData& bd = K->LL_GetData(k); if (*(bd.game_mtl_name)) { bd.game_mtl_idx = GMLib.GetMaterialIdx(*bd.game_mtl_name); R_ASSERT2(GMLib.GetMaterialByIdx(bd.game_mtl_idx)->Flags.is(SGameMtl::flDynamic), "Required dynamic game material"); } else { bd.game_mtl_idx = def_idx; } } }break; } } extern void clean_game_globals(); extern void init_game_globals(); void CGamePersistent::OnAppStart() { // load game materials GMLib.Load(); init_game_globals(); __super::OnAppStart(); m_pUI_core = xr_new<ui_core>(); m_pMainMenu = xr_new<CMainMenu>(); } void CGamePersistent::OnAppEnd() { if (m_pMainMenu->IsActive()) m_pMainMenu->Activate(false); xr_delete(m_pMainMenu); xr_delete(m_pUI_core); __super::OnAppEnd(); clean_game_globals(); GMLib.Unload(); } void CGamePersistent::Start(LPCSTR op) { __super::Start(op); } void CGamePersistent::Disconnect() { // destroy ambient particles CParticlesObject::Destroy(ambient_particles); __super::Disconnect(); // stop all played emitters ::Sound->stop_emitters(); m_game_params.m_e_game_type = eGameIDNoGame; } #include "xr_level_controller.h" void CGamePersistent::OnGameStart() { __super::OnGameStart(); UpdateGameType(); } void CGamePersistent::UpdateGameType() { __super::UpdateGameType(); m_game_params.m_e_game_type = eGameIDSingle; g_current_keygroup = _sp; } void CGamePersistent::OnGameEnd() { __super::OnGameEnd(); xr_delete(g_stalker_animation_data_storage); xr_delete(g_stalker_velocity_holder); } void CGamePersistent::WeathersUpdate() { if (g_pGameLevel && !g_dedicated_server) { CActor* actor = smart_cast<CActor*>(Level().CurrentViewEntity()); BOOL bIndoor = TRUE; if (actor) bIndoor = actor->renderable_ROS()->get_luminocity_hemi() < 0.05f; int data_set = (Random.randF() < (1.f - Environment().CurrentEnv->weight)) ? 0 : 1; CEnvDescriptor* const current_env = Environment().Current[0]; VERIFY(current_env); CEnvDescriptor* const _env = Environment().Current[data_set]; VERIFY(_env); CEnvAmbient* env_amb = _env->env_ambient; if (env_amb) { CEnvAmbient::SSndChannelVec& vec = current_env->env_ambient->get_snd_channels(); CEnvAmbient::SSndChannelVecIt I = vec.begin(); CEnvAmbient::SSndChannelVecIt E = vec.end(); for (u32 idx = 0; I != E; ++I, ++idx) { CEnvAmbient::SSndChannel& ch = **I; R_ASSERT(idx<20); if (ambient_sound_next_time[idx] == 0)//first { ambient_sound_next_time[idx] = Device.dwTimeGlobal + ch.get_rnd_sound_first_time(); } else if (Device.dwTimeGlobal > ambient_sound_next_time[idx]) { ref_sound& snd = ch.get_rnd_sound(); Fvector pos; float angle = ::Random.randF(PI_MUL_2); pos.x = _cos(angle); pos.y = 0; pos.z = _sin(angle); pos.normalize().mul(ch.get_rnd_sound_dist()).add(Device.vCameraPosition); pos.y += 10.f; snd.play_at_pos(0, pos); #ifdef DEBUG if (!snd._handle() && strstr(Core.Params, "-nosound")) continue; #endif // DEBUG VERIFY(snd._handle()); u32 _length_ms = iFloor(snd.get_length_sec()*1000.0f); ambient_sound_next_time[idx] = Device.dwTimeGlobal + _length_ms + ch.get_rnd_sound_time(); // Msg("- Playing ambient sound channel [%s] file[%s]",ch.m_load_section.c_str(),snd._handle()->file_name()); } } /* if (Device.dwTimeGlobal > ambient_sound_next_time) { ref_sound* snd = env_amb->get_rnd_sound(); ambient_sound_next_time = Device.dwTimeGlobal + env_amb->get_rnd_sound_time(); if (snd) { Fvector pos; float angle = ::Random.randF(PI_MUL_2); pos.x = _cos(angle); pos.y = 0; pos.z = _sin(angle); pos.normalize ().mul(env_amb->get_rnd_sound_dist()).add(Device.vCameraPosition); pos.y += 10.f; snd->play_at_pos (0,pos); } } */ // start effect if ((FALSE == bIndoor) && (0 == ambient_particles) && Device.dwTimeGlobal > ambient_effect_next_time) { CEnvAmbient::SEffect* eff = env_amb->get_rnd_effect(); if (eff) { Environment().wind_gust_factor = eff->wind_gust_factor; ambient_effect_next_time = Device.dwTimeGlobal + env_amb->get_rnd_effect_time(); ambient_effect_stop_time = Device.dwTimeGlobal + eff->life_time; ambient_effect_wind_start = Device.fTimeGlobal; ambient_effect_wind_in_time = Device.fTimeGlobal + eff->wind_blast_in_time; ambient_effect_wind_end = Device.fTimeGlobal + eff->life_time / 1000.f; ambient_effect_wind_out_time = Device.fTimeGlobal + eff->life_time / 1000.f + eff->wind_blast_out_time; ambient_effect_wind_on = true; ambient_particles = CParticlesObject::Create(eff->particles.c_str(), FALSE, false); Fvector pos; pos.add(Device.vCameraPosition, eff->offset); ambient_particles->play_at_pos(pos); if (eff->sound._handle()) eff->sound.play_at_pos(0, pos); Environment().wind_blast_strength_start_value = Environment().wind_strength_factor; Environment().wind_blast_strength_stop_value = eff->wind_blast_strength; if (Environment().wind_blast_strength_start_value == 0.f) { Environment().wind_blast_start_time.set(0.f, eff->wind_blast_direction.x, eff->wind_blast_direction.y, eff->wind_blast_direction.z); } else { Environment().wind_blast_start_time.set(0.f, Environment().wind_blast_direction.x, Environment().wind_blast_direction.y, Environment().wind_blast_direction.z); } Environment().wind_blast_stop_time.set(0.f, eff->wind_blast_direction.x, eff->wind_blast_direction.y, eff->wind_blast_direction.z); } } } if (Device.fTimeGlobal >= ambient_effect_wind_start && Device.fTimeGlobal <= ambient_effect_wind_in_time && ambient_effect_wind_on) { float delta = ambient_effect_wind_in_time - ambient_effect_wind_start; float t; if (delta != 0.f) { float cur_in = Device.fTimeGlobal - ambient_effect_wind_start; t = cur_in / delta; } else { t = 0.f; } Environment().wind_blast_current.slerp(Environment().wind_blast_start_time, Environment().wind_blast_stop_time, t); Environment().wind_blast_direction.set(Environment().wind_blast_current.x, Environment().wind_blast_current.y, Environment().wind_blast_current.z); Environment().wind_strength_factor = Environment().wind_blast_strength_start_value + t*(Environment().wind_blast_strength_stop_value - Environment().wind_blast_strength_start_value); } // stop if time exceed or indoor if (bIndoor || Device.dwTimeGlobal >= ambient_effect_stop_time) { if (ambient_particles) ambient_particles->Stop(); Environment().wind_gust_factor = 0.f; } if (Device.fTimeGlobal >= ambient_effect_wind_end && ambient_effect_wind_on) { Environment().wind_blast_strength_start_value = Environment().wind_strength_factor; Environment().wind_blast_strength_stop_value = 0.f; ambient_effect_wind_on = false; } if (Device.fTimeGlobal >= ambient_effect_wind_end && Device.fTimeGlobal <= ambient_effect_wind_out_time) { float delta = ambient_effect_wind_out_time - ambient_effect_wind_end; float t; if (delta != 0.f) { float cur_in = Device.fTimeGlobal - ambient_effect_wind_end; t = cur_in / delta; } else { t = 0.f; } Environment().wind_strength_factor = Environment().wind_blast_strength_start_value + t*(Environment().wind_blast_strength_stop_value - Environment().wind_blast_strength_start_value); } if (Device.fTimeGlobal > ambient_effect_wind_out_time && ambient_effect_wind_out_time != 0.f) { Environment().wind_strength_factor = 0.0; } // if particles not playing - destroy if (ambient_particles&&!ambient_particles->IsPlaying()) CParticlesObject::Destroy(ambient_particles); } } bool allow_intro() { #ifdef MASTER_GOLD if (g_SASH.IsRunning()) #else // #ifdef MASTER_GOLD if ((0 != strstr(Core.Params, "-nointro")) || g_SASH.IsRunning()) #endif // #ifdef MASTER_GOLD { return false; } else return true; } bool allow_logo() // AVO: skip NVIDIA and other logos at load time { if (0 != strstr(Core.Params, "-skiplogo")) { return false; } else { return true; } } void CGamePersistent::start_logo_intro() { if (Device.dwPrecacheFrame == 0) { m_intro_event.bind(this, &CGamePersistent::update_logo_intro); if (!g_dedicated_server && 0 == xr_strlen(m_game_params.m_game_or_spawn) && NULL == g_pGameLevel) { VERIFY(NULL == m_intro); m_intro = xr_new<CUISequencer>(); if (allow_logo()) // AVO: skip NVIDIA and other logos at load time { m_intro->Start("intro_logo"); Msg("intro_start intro_logo"); } Console->Hide(); } } } void CGamePersistent::update_logo_intro() { if (m_intro && (false == m_intro->IsActive())) { m_intro_event = 0; xr_delete(m_intro); Msg("intro_delete ::update_logo_intro"); Console->Execute("main_menu on"); } else if (!m_intro) { m_intro_event = 0; } } extern int g_keypress_on_start; void CGamePersistent::game_loaded() { if (Device.dwPrecacheFrame <= 2) { if (g_pGameLevel && g_pGameLevel->bReady && (allow_intro() && g_keypress_on_start) && load_screen_renderer.b_need_user_input && m_game_params.m_e_game_type == eGameIDSingle) { VERIFY(NULL == m_intro); m_intro = xr_new<CUISequencer>(); m_intro->Start("game_loaded"); Msg("intro_start game_loaded"); m_intro->m_on_destroy_event.bind(this, &CGamePersistent::update_game_loaded); } m_intro_event = 0; } } void CGamePersistent::update_game_loaded() { xr_delete(m_intro); Msg("intro_delete ::update_game_loaded"); start_game_intro(); } void CGamePersistent::start_game_intro() { if (!allow_intro()) { m_intro_event = 0; return; } if (g_pGameLevel && g_pGameLevel->bReady && Device.dwPrecacheFrame <= 2) { m_intro_event.bind(this, &CGamePersistent::update_game_intro); if (0 == stricmp(m_game_params.m_new_or_load, "new")) { VERIFY(NULL == m_intro); m_intro = xr_new<CUISequencer>(); m_intro->Start("intro_game"); Msg("intro_start intro_game"); } } } void CGamePersistent::update_game_intro() { if (m_intro && (false == m_intro->IsActive())) { xr_delete(m_intro); Msg("intro_delete ::update_game_intro"); m_intro_event = 0; } else if (!m_intro) { m_intro_event = 0; } } extern CUISequencer * g_tutorial; extern CUISequencer * g_tutorial2; void CGamePersistent::OnFrame() { if (Device.dwPrecacheFrame == 5 && m_intro_event.empty()) { m_intro_event.bind(this, &CGamePersistent::game_loaded); } if (g_tutorial2) { g_tutorial2->Destroy(); xr_delete(g_tutorial2); } if (g_tutorial && !g_tutorial->IsActive()) { xr_delete(g_tutorial); } if (0 == Device.dwFrame % 200) CUITextureMaster::FreeCachedShaders(); #ifdef DEBUG ++m_frame_counter; #endif if (!g_dedicated_server && !m_intro_event.empty()) m_intro_event(); if (!g_dedicated_server && Device.dwPrecacheFrame == 0 && !m_intro && m_intro_event.empty()) load_screen_renderer.stop(); if (!m_pMainMenu->IsActive()) m_pMainMenu->DestroyInternal(false); if (!g_pGameLevel) return; if (!g_pGameLevel->bReady) return; if (Device.Paused()) { #ifndef MASTER_GOLD if (Level().CurrentViewEntity()) { if (!g_actor || (g_actor->ID() != Level().CurrentViewEntity()->ID())) { CCustomMonster *custom_monster = smart_cast<CCustomMonster*>(Level().CurrentViewEntity()); if (custom_monster) // can be spectator in multiplayer custom_monster->UpdateCamera(); } else { CCameraBase* C = NULL; if (g_actor) { if (!Actor()->Holder()) C = Actor()->cam_Active(); else C = Actor()->Holder()->Camera(); Actor()->Cameras().UpdateFromCamera(C); Actor()->Cameras().ApplyDevice(VIEWPORT_NEAR); #ifdef DEBUG if (psActorFlags.test(AF_NO_CLIP)) { Actor()->dbg_update_cl = 0; Actor()->dbg_update_shedule = 0; Device.dwTimeDelta = 0; Device.fTimeDelta = 0.01f; Actor()->UpdateCL(); Actor()->shedule_Update(0); Actor()->dbg_update_cl = 0; Actor()->dbg_update_shedule = 0; CSE_Abstract* e = Level().Server->ID_to_entity(Actor()->ID()); VERIFY(e); CSE_ALifeCreatureActor* s_actor = smart_cast<CSE_ALifeCreatureActor*>(e); VERIFY(s_actor); xr_vector<u16>::iterator it = s_actor->children.begin(); for (; it != s_actor->children.end(); it++) { CObject* obj = Level().Objects.net_Find(*it); if (obj && Engine.Sheduler.Registered(obj)) { obj->dbg_update_shedule = 0; obj->dbg_update_cl = 0; obj->shedule_Update(0); obj->UpdateCL(); obj->dbg_update_shedule = 0; obj->dbg_update_cl = 0; } } } #endif // DEBUG } } } #else // MASTER_GOLD if (g_actor) { CCameraBase* C = NULL; if(!Actor()->Holder()) C = Actor()->cam_Active(); else C = Actor()->Holder()->Camera(); Actor()->Cameras().UpdateFromCamera (C); Actor()->Cameras().ApplyDevice (VIEWPORT_NEAR); } #endif // MASTER_GOLD } __super::OnFrame(); if (!Device.Paused()) Engine.Sheduler.Update(); // update weathers ambient if (!Device.Paused()) WeathersUpdate(); if (0 != pDemoFile) { if (Device.dwTimeGlobal > uTime2Change) { // Change level + play demo if (pDemoFile->elapsed() < 3) pDemoFile->seek(0); // cycle // Read params string512 params; pDemoFile->r_string(params, sizeof(params)); string256 o_server, o_client, o_demo; u32 o_time; sscanf(params, "%[^,],%[^,],%[^,],%d", o_server, o_client, o_demo, &o_time); // Start _new level + demo Engine.Event.Defer("KERNEL:disconnect"); Engine.Event.Defer("KERNEL:start", size_t(xr_strdup(_Trim(o_server))), size_t(xr_strdup(_Trim(o_client)))); Engine.Event.Defer("GAME:demo", size_t(xr_strdup(_Trim(o_demo))), u64(o_time)); uTime2Change = 0xffffffff; // Block changer until Event received } } #ifdef DEBUG if ((m_last_stats_frame + 1) < m_frame_counter) profiler().clear(); #endif UpdateDof(); } #include "game_sv_single.h" #include "xrServer.h" #include "UIGameCustom.h" #include "ui/UIMainIngameWnd.h" #include "ui/UIPdaWnd.h" void CGamePersistent::OnEvent(EVENT E, u64 P1, u64 P2) { if (E == eQuickLoad) { if (Device.Paused()) Device.Pause(FALSE, TRUE, TRUE, "eQuickLoad"); if (CurrentGameUI()) { CurrentGameUI()->HideShownDialogs(); CurrentGameUI()->UIMainIngameWnd->reset_ui(); CurrentGameUI()->GetPdaMenu().Reset(); } if (g_tutorial) g_tutorial->Stop(); if (g_tutorial2) g_tutorial2->Stop(); LPSTR saved_name = (LPSTR) (P1); Level().remove_objects(); game_sv_Single *game = smart_cast<game_sv_Single*>(Level().Server->game); R_ASSERT(game); game->restart_simulator(saved_name); xr_free(saved_name); return; } else if (E == eDemoStart) { string256 cmd; LPCSTR demo = LPCSTR(P1); xr_sprintf(cmd, "demo_play %s", demo); Console->Execute(cmd); xr_free(demo); uTime2Change = Device.TimerAsync() + u32(P2) * 1000; } } void CGamePersistent::Statistics(CGameFont* F) { #ifdef DEBUG # ifndef _EDITOR m_last_stats_frame = m_frame_counter; profiler().show_stats(F, !!psAI_Flags.test(aiStats)); # endif #endif } float CGamePersistent::MtlTransparent(u32 mtl_idx) { return GMLib.GetMaterialByIdx((u16) mtl_idx)->fVisTransparencyFactor; } static BOOL bRestorePause = FALSE; static BOOL bEntryFlag = TRUE; void CGamePersistent::OnAppActivate() { bool bIsMP = (g_pGameLevel && Level().game && GameID() != eGameIDSingle); bIsMP &= !Device.Paused(); if (!bIsMP) { Device.Pause(FALSE, !bRestorePause, TRUE, "CGP::OnAppActivate"); } else { Device.Pause(FALSE, TRUE, TRUE, "CGP::OnAppActivate MP"); } bEntryFlag = TRUE; } void CGamePersistent::OnAppDeactivate() { if (!bEntryFlag) return; bool bIsMP = (g_pGameLevel && Level().game && GameID() != eGameIDSingle); bRestorePause = FALSE; if (!bIsMP) { bRestorePause = Device.Paused(); Device.Pause(TRUE, TRUE, TRUE, "CGP::OnAppDeactivate"); } else { Device.Pause(TRUE, FALSE, TRUE, "CGP::OnAppDeactivate MP"); } bEntryFlag = FALSE; } bool CGamePersistent::OnRenderPPUI_query() { return MainMenu()->OnRenderPPUI_query(); // enable PP or not } extern void draw_wnds_rects(); void CGamePersistent::OnRenderPPUI_main() { // always MainMenu()->OnRenderPPUI_main(); draw_wnds_rects(); } void CGamePersistent::OnRenderPPUI_PP() { MainMenu()->OnRenderPPUI_PP(); } #include "string_table.h" #include "../xrEngine/x_ray.h" void CGamePersistent::LoadTitle(bool change_tip, shared_str map_name) { pApp->LoadStage(); if (change_tip) { LPCSTR tip_header; LPCSTR tip_title; LPCSTR tip_text; luabind::functor<LPCSTR> m_functor; R_ASSERT(ai().script_engine().functor("loadscreen.get_tip_header", m_functor)); tip_header = m_functor(map_name.c_str()); R_ASSERT(ai().script_engine().functor("loadscreen.get_tip_title", m_functor)); tip_title = m_functor(map_name.c_str()); R_ASSERT(ai().script_engine().functor("loadscreen.get_tip_text", m_functor)); tip_text = m_functor(map_name.c_str()); pApp->LoadTitleInt(tip_header, tip_title, tip_text); } } bool CGamePersistent::CanBePaused() { return true; } void CGamePersistent::SetPickableEffectorDOF(bool bSet) { m_bPickableDOF = bSet; if (!bSet) RestoreEffectorDOF(); } void CGamePersistent::GetCurrentDof(Fvector3& dof) { dof = m_dof[1]; } void CGamePersistent::SetBaseDof(const Fvector3& dof) { m_dof[0] = m_dof[1] = m_dof[2] = m_dof[3] = dof; } void CGamePersistent::SetEffectorDOF(const Fvector& needed_dof) { if (m_bPickableDOF) return; m_dof[0] = needed_dof; m_dof[2] = m_dof[1]; //current } void CGamePersistent::RestoreEffectorDOF() { SetEffectorDOF(m_dof[3]); } #include "hudmanager.h" // m_dof [4]; // 0-dest 1-current 2-from 3-original void CGamePersistent::UpdateDof() { static float diff_far = pSettings->r_float("zone_pick_dof", "far");//70.0f; static float diff_near = pSettings->r_float("zone_pick_dof", "near");//-70.0f; if (m_bPickableDOF) { Fvector pick_dof; pick_dof.y = HUD().GetCurrentRayQuery().range; pick_dof.x = pick_dof.y + diff_near; pick_dof.z = pick_dof.y + diff_far; m_dof[0] = pick_dof; m_dof[2] = m_dof[1]; //current } if (m_dof[1].similar(m_dof[0])) return; float td = Device.fTimeDelta; Fvector diff; diff.sub(m_dof[0], m_dof[2]); diff.mul(td / 0.2f); //0.2 sec m_dof[1].add(diff); (m_dof[0].x < m_dof[2].x) ? clamp(m_dof[1].x, m_dof[0].x, m_dof[2].x) : clamp(m_dof[1].x, m_dof[2].x, m_dof[0].x); (m_dof[0].y < m_dof[2].y) ? clamp(m_dof[1].y, m_dof[0].y, m_dof[2].y) : clamp(m_dof[1].y, m_dof[2].y, m_dof[0].y); (m_dof[0].z < m_dof[2].z) ? clamp(m_dof[1].z, m_dof[0].z, m_dof[2].z) : clamp(m_dof[1].z, m_dof[2].z, m_dof[0].z); } #include "ui\uimainingamewnd.h" void CGamePersistent::OnSectorChanged(int sector) { if (CurrentGameUI()) CurrentGameUI()->UIMainIngameWnd->OnSectorChanged(sector); } void CGamePersistent::OnAssetsChanged() { IGame_Persistent::OnAssetsChanged(); CStringTable().rescan(); }
0
0.969648
1
0.969648
game-dev
MEDIA
0.794829
game-dev
0.937196
1
0.937196
Shmaug/UnityPlanets
8,674
Assets/Scripts/Ship.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(Gravity))] [RequireComponent(typeof(Animation))] public class Ship : MonoBehaviour { public MeshCollider shipCollider; public bool landed = false; public float maxPlanetarySpeed = 300f; public float maxSpaceSpeed = 1000f; public float warpSpeed = 1e6f; public float landingSpeed = 5f; public float landingDistance = 30f; public float rotSpeed = 30f; [Space] public Transform cameraCockpit; public LaserGun[] guns; [Space] public UnityEngine.UI.Text warpText; public UnityEngine.UI.Text speedText; public UnityEngine.UI.Text altitudeText; public UnityEngine.UI.Text radarAltText; public UnityEngine.UI.Text landText; public UnityEngine.UI.Text pressureText; public RectTransform landProgressBar; public UnityEngine.UI.RawImage atmoSliderBar; public RectTransform atmoSliderIcon; [Space] public AudioClip midHumStart; public AudioClip midHumLoop; public AudioClip midHumEnd; [System.NonSerialized] public Vector3 throttle; [System.NonSerialized] public Vector3 pitchYawRoll; [System.NonSerialized] public bool firing; [System.NonSerialized] public bool engageWarp = false; public bool canLand { get; private set; } public Vector3 landPos { get; private set; } public Vector3 landUp { get; private set; } public bool landing { get; private set; } public float landProgress { get; private set; } = 0f; public bool canWarp { get; private set; } public bool warping { get; private set; } public float warpEngageTimer { get; private set; } = 5f; Animation anim; [System.NonSerialized] public Rigidbody rbody; Gravity gravity; void Start() { anim = GetComponent<Animation>(); rbody = GetComponent<Rigidbody>(); gravity = GetComponent<Gravity>(); if (ScaleSpace.instance) ScaleSpace.instance.RegisterFloatingOrigin(transform); //anim["ship_geardown"].layer = 0; //anim["ship_gearup"].layer = 0; //anim["ship_cockpitopen"].layer = 1; //anim["ship_cockpitclose"].layer = 1; } void OnLevelWasLoaded(int level) { if (ScaleSpace.instance) ScaleSpace.instance.RegisterFloatingOrigin(transform); } void FixedUpdate() { if (!landed && !landing) { float spd; if (warping) { spd = warpSpeed; rbody.velocity = transform.forward * warpSpeed; } else { if (gravity.planet) { double alt = gravity.distToPlanet - (gravity.planet.radius + gravity.planet.waterHeight); double d = gravity.planet.AtmosphereDensity(gravity.distToPlanet); double h = 1f - Mathd.Clamp01(alt / gravity.planet.atmosphereHeight); d = Mathd.Clamp01(d + h * h); spd = Mathf.Lerp(maxSpaceSpeed, maxPlanetarySpeed, (float)d); } else { spd = maxSpaceSpeed; } Vector3 target = transform.rotation * throttle * spd; rbody.AddForce((target - rbody.velocity) * .95f, ForceMode.Acceleration); rbody.AddRelativeTorque(pitchYawRoll, ForceMode.Acceleration); } } } void Update() { canWarp = !gravity.planet || gravity.distToPlanet > gravity.planet.radius + gravity.planet.atmosphereHeight * 1.5; if (engageWarp && !warping && canWarp) { warpEngageTimer -= Time.deltaTime; if (warpEngageTimer <= 0f) { warping = true; rbody.velocity = rbody.velocity.normalized * warpSpeed; } } else warpEngageTimer = 5f; // weapons if (landed) firing = false; for (int i = 0; i < guns.Length; i++) guns[i].firing = firing; canLand = false; if (gravity.planet) { // landing RaycastHit rh; if (!landing && !landed && Physics.Raycast(transform.position, (-gravity.up + .5f * rbody.velocity).normalized, out rh, landingDistance)) { if (Vector3.Dot(rh.normal, gravity.up) > .9f) { canLand = true; landPos = rh.point; landUp = rh.normal; } } } UpdateUI(); } void UpdateUI() { if (gravity.planet) { double alt = gravity.distToPlanet - (gravity.planet.radius + gravity.planet.waterHeight); altitudeText.text = ScaleSpace.DisplayDistanceMeasure(alt); radarAltText.text = ScaleSpace.DisplayDistanceMeasure(gravity.distToPlanet - gravity.planet.GetHeight(gravity.planet.rotation.inverse * (Vector3d)gravity.up)); // atmosphere UI if (gravity.planet.hasAtmosphere) { atmoSliderBar.gameObject.SetActive(true); atmoSliderIcon.anchoredPosition = new Vector2( (float)Mathd.Clamp01(alt / gravity.planet.atmosphereHeight) * atmoSliderBar.rectTransform.rect.width, 0); atmoSliderBar.materialForRendering.SetFloat("_Hr", gravity.planet.reyleighScaleDepth); atmoSliderBar.materialForRendering.SetFloat("_Hm", gravity.planet.mieScaleDepth); double pressure = gravity.planet.AtmosphereDensity(gravity.distToPlanet); pressureText.text = pressure.ToString("f4") + " atm"; } else { pressureText.text = "------ atm"; atmoSliderBar.gameObject.SetActive(false); } } else { altitudeText.text = "------ m"; radarAltText.text = "------ m"; pressureText.text = "------ atm"; atmoSliderBar.gameObject.SetActive(false); } landText.color = landing ? new Color(1f, .5f, 0f) : canLand ? Color.green : Color.white * .65f; landProgressBar.sizeDelta = new Vector2((landProgressBar.parent as RectTransform).rect.width * landProgress, landProgressBar.sizeDelta.y); speedText.text = ScaleSpace.DisplaySpeedMeasure(rbody.velocity.magnitude); if (warping) { warpText.text = "WARPING"; warpText.color = Color.white; } else { if (canWarp) { if (engageWarp) { warpText.text = "WARP: " + (int)(warpEngageTimer + .5f); warpText.color = Color.white; } else { warpText.color = Color.green; warpText.text = "WARP AVAILABLE"; } } else { warpText.color = new Color(.9f, 0f, 0f); warpText.text = "WARP UNAVAILABLE"; } } } public void ExitWarp() { warping = false; rbody.velocity = transform.forward * maxSpaceSpeed; } public void TakeOff() { if (!landed) return; landed = false; shipCollider.convex = true; rbody.isKinematic = false; //anim.Play("ship_gearup", PlayMode.StopSameLayer); } public void Land() { if (landing || !canLand) return; landing = true; //anim.Play("ship_geardown", PlayMode.StopSameLayer); StartCoroutine(LandSequence()); } IEnumerator LandSequence() { rbody.isKinematic = true; shipCollider.convex = false; Vector3 toTarget; float dist; float startDist = (transform.position - landPos).magnitude; Quaternion startRot = transform.rotation; Quaternion targRot = Quaternion.FromToRotation(transform.up, landUp) * transform.rotation; while (true) { toTarget = landPos - transform.position; dist = toTarget.magnitude; if (dist < .2f) break; toTarget /= dist; landProgress = 1f - dist / startDist; transform.rotation = Quaternion.Lerp(startRot, targRot, landProgress); transform.position += toTarget * Mathf.Min(dist, Time.deltaTime * landingSpeed); yield return new WaitForFixedUpdate(); } landProgress = 0; transform.position = landPos; transform.rotation = targRot; rbody.velocity = Vector3.zero; rbody.angularVelocity = Vector3.zero; landing = false; landed = true; } void OnOriginChange(Vector3 delta) { landPos -= delta; } }
0
0.713745
1
0.713745
game-dev
MEDIA
0.950158
game-dev
0.957493
1
0.957493
DaFuqs/Spectrum
1,634
src/main/java/de/dafuqs/spectrum/compat/modonomicon/client/pages/BookChecklistPageRenderer.java
package de.dafuqs.spectrum.compat.modonomicon.client.pages; import com.klikli_dev.modonomicon.book.*; import com.klikli_dev.modonomicon.client.gui.book.entry.*; import com.klikli_dev.modonomicon.client.render.page.*; import com.klikli_dev.modonomicon.data.*; import de.dafuqs.revelationary.api.advancements.*; import de.dafuqs.spectrum.compat.modonomicon.pages.*; import net.minecraft.network.chat.*; import net.minecraft.resources.*; import java.util.*; public class BookChecklistPageRenderer extends BookTextPageRenderer { public BookChecklistPageRenderer(BookChecklistPage page) { super(page); } @Override public void onBeginDisplayPage(BookEntryScreen parentScreen, int left, int top) { if (!(page instanceof BookChecklistPage checklistPage)) return; if (!(page.getText() instanceof RenderedBookTextHolder renderedText)) return; super.onBeginDisplayPage(parentScreen, left, top); List<MutableComponent> renderedTexts = renderedText.getRenderedText(); ResourceLocation font = BookDataManager.Client.get().safeFont(this.page.getBook().getFont()); int i = 0; for (Map.Entry<ResourceLocation, BookTextHolder> entry : checklistPage.getChecklist().entrySet()) { boolean hasAchievement = AdvancementHelper.hasAdvancementClient(entry.getKey()); renderedTexts.get(i).withStyle(Style.EMPTY.withStrikethrough(hasAchievement).withFont(font)); List<Component> siblings = renderedTexts.get(i).getSiblings(); siblings.removeLast(); siblings.add(Component.literal(hasAchievement ? " ✔" : "")); i++; } } }
0
0.702735
1
0.702735
game-dev
MEDIA
0.895253
game-dev
0.833048
1
0.833048
Simply-Love/Simply-Love-SM5
12,116
Scripts/SL_ITL.lua
-- ----------------------------------------------------------------------- IsItlSong = function(player) local song = GAMESTATE:GetCurrentSong() local song_dir = song:GetSongDir() local group = string.lower(song:GetGroupName()) local pn = ToEnumShortString(player) return string.find(group, "itl online 2025") or string.find(group, "itl 2025") or SL[pn].ITLData["pathMap"][song_dir] ~= nil end IsItlActive = function() -- The file is only written to while the event is active. -- These are just placeholder dates. -- local startTimestamp = 20230317 -- local endTimestamp = 20240420 -- local year = Year() -- local month = MonthOfYear()+1 -- local day = DayOfMonth() -- local today = year * 10000 + month * 100 + day -- return startTimestamp <= today and today <= endTimestamp -- Assume ITL is always active. This helps when we close and reopen the event. return true end -- ----------------------------------------------------------------------- -- The ITL file is a JSON file that contains two mappings: -- -- { -- pathMap = { -- '<song_dir>': '<song_hash>', -- }, -- hashMap = { -- '<song_hash': { ..itl metadata .. } -- } -- } -- -- The pathMap maps a song directory corresponding to an ITL chart to its song hash -- The hashMap is a mapping from that hash to the relevant data stored for the event. -- -- This set up lets us display song wheel grades for ITL both from playing within the -- ITL pack and also outside of it. -- Note that songs resynced for ITL but played outside of the pack will not be covered in the pathMap. local itlFilePath = "itl2025.json" local TableContainsData = function(t) if t == nil then return false end for _, _ in pairs(t) do return true end return false end -- Takes the ITLData loaded in memory and writes it to the local profile. WriteItlFile = function(player) local pn = ToEnumShortString(player) -- No data to write, return early. if (not TableContainsData(SL[pn].ITLData["pathMap"]) and not TableContainsData(SL[pn].ITLData["hashMap"])) then return end local profile_slot = { [PLAYER_1] = "ProfileSlot_Player1", [PLAYER_2] = "ProfileSlot_Player2" } local dir = PROFILEMAN:GetProfileDir(profile_slot[player]) -- We require an explicit profile to be loaded. if not dir or #dir == 0 then return end local path = dir .. itlFilePath local f = RageFileUtil:CreateRageFile() if f:Open(path, 2) then f:Write(JsonEncode(SL[pn].ITLData)) f:Close() end f:destroy() end -- Generally to be called only once when a profile is loaded. -- This parses the ITL data file and stores it in memory for the song wheel to reference. ReadItlFile = function(player) local profile_slot = { [PLAYER_1] = "ProfileSlot_Player1", [PLAYER_2] = "ProfileSlot_Player2" } local dir = PROFILEMAN:GetProfileDir(profile_slot[player]) local pn = ToEnumShortString(player) -- We require an explicit profile to be loaded. if not dir or #dir == 0 then return end local path = dir .. itlFilePath local itlData = { ["pathMap"] = {}, ["hashMap"] = {}, } if FILEMAN:DoesFileExist(path) then local f = RageFileUtil:CreateRageFile() local existing = "" if f:Open(path, 1) then existing = f:Read() f:Close() end f:destroy() itlData = JsonDecode(existing) end SL[pn].ITLData = itlData end -- EX score is a number like 92.67 GetITLPointsForSong = function(passingPoints, maxScoringPoints, exScore) local scalar = 40.0 local curve = (math.pow(scalar, math.max(0, exScore) / scalar) - 1) * (100.0 / (math.pow(scalar, 100 / scalar) - 1.0)) -- Helper function to round to a specific number of decimal places. -- We want 100% EX to actually grant 100% of the points. -- We don't want to lose out on any single points if possible. E.g. If -- 100% EX returns a number like 0.9999999999999997 and the chart points is -- 6500, then 6500 * 0.9999999999999997 = 6499.99999999999805, where -- flooring would give us 6499 which is wrong. local roundPlaces = function(x, places) local factor = 10 ^ places return math.floor(x * factor + 0.5) / factor end local percent = roundPlaces(curve / 100.0, 6) local scoringPoints = math.floor(maxScoringPoints * percent) return passingPoints + scoringPoints end -- Helper function used within UpdateItlData() below. -- Curates all the ITL data to be written to the ITL file for the played song. local DataForSong = function(player, prevData) local GetClearType = function(judgments) -- 1 = Pass -- 2 = FGC -- 3 = FEC -- 4 = FFC -- 5 = FFPC local clearType = 1 -- Dropping a hold or roll will always be a Pass local droppedHolds = judgments["totalRolls"] - judgments["Rolls"] local droppedRolls = (judgments["totalHolds"] - judgments["Holds"]) if droppedHolds > 0 or droppedRolls > 0 then return 1 end local totalTaps = judgments["Miss"] if judgments["W5"] ~= nil then totalTaps = totalTaps + judgments["W5"] end if judgments["W4"] ~= nil then totalTaps = totalTaps + judgments["W4"] end if totalTaps == 0 then clearType = 2 end totalTaps = totalTaps + judgments["W3"] if totalTaps == 0 then clearType = 3 end totalTaps = totalTaps + judgments["W2"] if totalTaps == 0 then clearType = 4 end totalTaps = totalTaps + judgments["W1"] if totalTaps == 0 then clearType = 5 end return clearType end local pn = ToEnumShortString(player) local steps = GAMESTATE:GetCurrentSteps(player) local chartName = steps:GetChartName() -- Note that playing OUTSIDE of the ITL pack will result in 0 points for all upscores. -- Technically this number isn't displayed, but players can opt to swap the EX score in the -- wheel with this value instead if they prefer. function ParseNumbers(input) local num1, num2 = input:match("(%d+)%s+%(P%)%s+%+%s+(%d+)%s+%(S%)") return tonumber(num1) or nil, tonumber(num2) or nil end local passingPoints, maxScoringPoints = ParseNumbers(chartName) if passingPoints == nil then -- See if we already have these points stored if we failed to parse it. if prevData ~= nil and prevData["passingPoints"] ~= nil then passingPoints = prevData["passingPoints"] -- Otherwise we don't know how many points this chart is. Default to 0. else passingPoints = 0 end end if maxScoringPoints == nil then -- See if we already have these points stored if we failed to parse it. if prevData ~= nil and prevData["maxScoringPoints"] ~= nil then maxScoringPoints = prevData["maxScoringPoints"] -- Otherwise we don't know how many points this chart is. Default to 0. else maxScoringPoints = 0 end end local maxPoints = passingPoints + maxScoringPoints -- Assume C-Mod is okay by default. local noCmod = false if prevData == nil or prevData["noCmod"] == nil then -- If we have no prior play data data for this ITL song, or the noCmod bit hasn't been -- calculated, parse the subtitle to see if this chart explicitly calls for noCmod. local song = GAMESTATE:GetCurrentSong() local subtitle = song:GetDisplaySubTitle():lower() if string.find(subtitle, "no cmod") then noCmod = true end else -- If the bit exists then read it from the previous data. -- My boy De Morgan says the below condition is the exact same as the else but my -- computer brain is tired and I just want to make sure. if prevData ~= nil and prevData["noCmod"] ~= nil then noCmod = prevData["noCmod"] end end local year = Year() local month = MonthOfYear()+1 local day = DayOfMonth() local judgments = GetExJudgmentCounts(player) local ex = CalculateExScore(player) local clearType = GetClearType(judgments) local points = GetITLPointsForSong(passingPoints, maxScoringPoints, ex) local usedCmod = GAMESTATE:GetPlayerState(pn):GetPlayerOptions("ModsLevel_Preferred"):CMod() ~= nil local date = ("%04d-%02d-%02d"):format(year, month, day) return { ["judgments"] = judgments, ["ex"] = ex * 100, ["clearType"] = clearType, ["points"] = points, ["usedCmod"] = usedCmod, ["date"] = date, ["noCmod"] = noCmod, ["passingPoints"] = passingPoints, ["maxScoringPoints"] = maxScoringPoints, ["maxPoints"] = maxPoints, } end -- Should be called during ScreenEvaluation to update the ITL data loaded. -- Will also write the contents to the file. UpdateItlData = function(player) local pn = ToEnumShortString(player) local stats = STATSMAN:GetCurStageStats():GetPlayerStageStats(player) -- Do the same validation as GrooveStats. -- This checks important things like timing windows, addition/removal of arrows, etc. local _, valid = ValidForGrooveStats(player) -- ITL additionally requires the music rate to be 1.00x. local so = GAMESTATE:GetSongOptionsObject("ModsLevel_Song") local rate = so:MusicRate() -- We also require mines to be on. local po = GAMESTATE:GetPlayerState(player):GetPlayerOptions("ModsLevel_Preferred") local minesEnabled = not po:NoMines() -- We also require all the windows to be enabled. -- ITG mode is the only mode that has all the windows enabled by default. local allWindowsEnabled = SL.Global.GameMode == "ITG" for enabled in ivalues(SL[pn].ActiveModifiers.TimingWindows) do allWindowsEnabled = allWindowsEnabled and enabled end if (GAMESTATE:IsHumanPlayer(player) and valid and rate == 1.0 and minesEnabled and not stats:GetFailed() and allWindowsEnabled) then local hash = SL[pn].Streams.Hash local hashMap = SL[pn].ITLData["hashMap"] local prevData = nil if hashMap ~= nil and hashMap[hash] ~= nil then prevData = hashMap[hash] end local data = DataForSong(player, prevData) -- C-Modded a No CMOD chart. Don't save this score. if data["noCmod"] and data["usedCmod"] then return end -- Update the pathMap as needed. local song = GAMESTATE:GetCurrentSong() local song_dir = song:GetSongDir() if song_dir ~= nil and #song_dir ~= 0 then local pathMap = SL[pn].ITLData["pathMap"] pathMap[song_dir] = hash end -- Then maybe update the hashMap. local updated = false if hashMap[hash] == nil then -- New score, just copy things over. hashMap[hash] = { ["judgments"] = DeepCopy(data["judgments"]), ["ex"] = data["ex"], ["clearType"] = data["clearType"], ["points"] = data["points"], ["usedCmod"] = data["usedCmod"], ["date"] = data["date"], ["noCmod"] = data["noCmod"], ["passingPoints"] = data["passingPoints"], ["maxScoringPoints"] = data["maxScoringPoints"], ["maxPoints"] = data["maxPoints"], } updated = true else if data["ex"] >= hashMap[hash]["ex"] then hashMap[hash]["ex"] = data["ex"] -- hashMap[hash]["points"] = data["points"] if data["ex"] > hashMap[hash]["ex"] then -- EX count is strictly better, copy the judgments over. hashMap[hash]["judgments"] = DeepCopy(data["judgments"]) updated = true else -- EX count is tied. -- "Smart" update judgment counts by picking the one with the highest top judgment. local better = false local keys = { "W0", "W1", "W2", "W3", "W4", "W5", "Miss" } for key in ivalues(keys) do local prev = hashMap[hash]["judgments"][key] local cur = data["judgments"][key] -- If both windows are defined, take the greater one. -- If current is defined but previous is not, then current is better. if (cur ~= nil and prev ~= nil and cur > prev) or (cur ~= nil and prev == nil) then better = true break end end if better then hashMap[hash]["judgments"] = DeepCopy(data["judgments"]) updated = true end end end if data["clearType"] > hashMap[hash]["clearType"] then hashMap[hash]["clearType"] = data["clearType"] updated = true end if updated then hashMap[hash]["usedCmod"] = data["usedCmod"] hashMap[hash]["date"] = data["date"] hashMap[hash]["noCmod"] = data["noCmod"] hashMap[hash]["passingPoints"] = data["passingPoints"] hashMap[hash]["maxScoringPoints"] = data["maxScoringPoints"] hashMap[hash]["maxPoints"] = data["maxPoints"] end end if updated then WriteItlFile(player) end end end
0
0.925023
1
0.925023
game-dev
MEDIA
0.679281
game-dev
0.987978
1
0.987978
Sean-Bradley/First-Car-Shooter
15,612
src/client/player.ts
import * as THREE from 'three' import * as CANNON from 'cannon-es' import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader' import Physics from './physics' import { Lensflare, LensflareElement, } from 'three/examples/jsm/objects/Lensflare.js' import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer' export default class Player { private scene: THREE.Scene private physics: Physics private frameMesh = new THREE.Mesh() private turretPivot = new THREE.Object3D() private turretMesh = new THREE.Mesh() private wheelLFMesh = new THREE.Group() private wheelRFMesh = new THREE.Group() private wheelLBMesh = new THREE.Group() private wheelRBMesh = new THREE.Group() private bulletMesh = [new THREE.Mesh(), new THREE.Mesh(), new THREE.Mesh()] private lastBulletCounter = [-1, -1, -1] //used to decide if a bullet should instantly be repositioned or smoothly lerped partIds: number[] = [] private frameBody: CANNON.Body private wheelLFBody: CANNON.Body private wheelRFBody: CANNON.Body private wheelLBBody: CANNON.Body private wheelRBBody: CANNON.Body enabled = false private screenName = '' private lastScreenName = '' private targetPosFrame = new THREE.Vector3() private targetPosTurret = new THREE.Vector3() private targetPosWheelLF = new THREE.Vector3() private targetPosWheelRF = new THREE.Vector3() private targetPosWheelLB = new THREE.Vector3() private targetPosWheelRB = new THREE.Vector3() private listener: THREE.AudioListener carSound: THREE.PositionalAudio private shootSound: THREE.PositionalAudio private lensflares = [new Lensflare(), new Lensflare(), new Lensflare()] private annotationDiv = document.createElement('div') constructor( scene: THREE.Scene, physics: Physics, listener: THREE.AudioListener ) { this.scene = scene this.physics = physics this.listener = listener const pipesMaterial = new THREE.MeshStandardMaterial() pipesMaterial.color = new THREE.Color('#ffffff') pipesMaterial.refractionRatio = 0 pipesMaterial.roughness = 0.2 pipesMaterial.metalness = 1 const audioLoader = new THREE.AudioLoader() const carSound = new THREE.PositionalAudio(this.listener) audioLoader.load('sounds/engine.wav', (buffer) => { carSound.setBuffer(buffer) carSound.setVolume(0.5) }) this.carSound = carSound const shootSound = new THREE.PositionalAudio(this.listener) audioLoader.load('sounds/rocket.ogg', (buffer) => { shootSound.setBuffer(buffer) shootSound.setVolume(2) }) this.shootSound = shootSound const flareTexture = new THREE.TextureLoader().load('img/lensflare0.png') this.lensflares.forEach((l) => { l.addElement( new LensflareElement( flareTexture, 200, 0, new THREE.Color(0xffa500) ) ) }) const loader = new GLTFLoader() loader.load( 'models/frame.glb', (gltf) => { this.frameMesh = gltf.scene.children[0] as THREE.Mesh this.frameMesh.material = pipesMaterial this.frameMesh.castShadow = true scene.add(this.frameMesh) this.carSound.loop = true this.frameMesh.add(this.carSound) this.frameMesh.add(this.shootSound) this.turretPivot = new THREE.Object3D() this.turretPivot.position.y = 1.0 this.turretPivot.position.z = 0.5 this.frameMesh.add(this.turretPivot) const turretGeometry = new THREE.CylinderGeometry(0.2, 0.2, 1.5) turretGeometry.rotateX(Math.PI / 2) turretGeometry.translate(0, 0, -0.5) this.turretMesh = new THREE.Mesh(turretGeometry, pipesMaterial) this.turretMesh.castShadow = true scene.add(this.turretMesh) // bullets for (let i = 0; i < 3; i++) { this.bulletMesh[i].geometry = new THREE.SphereGeometry( 0.3, 2, 2 ) this.bulletMesh[i].material = new THREE.MeshBasicMaterial({ color: 0xffa500, wireframe: true, }) this.bulletMesh[i].castShadow = true scene.add(this.bulletMesh[i]) this.bulletMesh[i].add(this.lensflares[i]) } loader.load( 'models/tyre.glb', (gltf) => { this.wheelLFMesh = gltf.scene this.wheelLFMesh.children[0].castShadow = true this.wheelRFMesh = this.wheelLFMesh.clone() this.wheelLBMesh = this.wheelLFMesh.clone() this.wheelRBMesh = this.wheelLFMesh.clone() this.wheelLFMesh.scale.setScalar(0.85) this.wheelRFMesh.scale.setScalar(0.85) scene.add(this.wheelLFMesh) scene.add(this.wheelRFMesh) scene.add(this.wheelLBMesh) scene.add(this.wheelRBMesh) }, (xhr) => { console.log((xhr.loaded / xhr.total) * 100 + '% loaded') }, (error) => { console.log(error) } ) this.annotationDiv.className = 'annotationLabel' this.annotationDiv.innerHTML = this.screenName const annotationLabel = new CSS2DObject(this.annotationDiv) annotationLabel.position.copy(this.turretMesh.position) this.turretMesh.add(annotationLabel) }, (xhr) => { console.log((xhr.loaded / xhr.total) * 100 + '% loaded') }, (error) => { console.log(error) } ) this.frameBody = new CANNON.Body({ mass: 0 }) this.frameBody.addShape( new CANNON.Sphere(0.9), new CANNON.Vec3(0, 0.5, 0.2) ) this.frameBody.position.set(0, 0, 0) //this.physics.world.addBody(this.frameBody) this.partIds.push(this.frameBody.id) const wheelLFShape = new CANNON.Sphere(0.35) this.wheelLFBody = new CANNON.Body({ mass: 0, material: this.physics.wheelMaterial, }) this.wheelLFBody.addShape(wheelLFShape) this.wheelLFBody.position.set(-2, 0, -2) //this.physics.world.addBody(this.wheelLFBody) this.partIds.push(this.wheelLFBody.id) const wheelRFShape = new CANNON.Sphere(0.35) this.wheelRFBody = new CANNON.Body({ mass: 0, material: this.physics.wheelMaterial, }) this.wheelRFBody.addShape(wheelRFShape) this.wheelRFBody.position.set(2, 0, -2) //this.physics.world.addBody(this.wheelRFBody) this.partIds.push(this.wheelRFBody.id) const wheelLBShape = new CANNON.Sphere(0.4) this.wheelLBBody = new CANNON.Body({ mass: 0, material: this.physics.wheelMaterial, }) this.wheelLBBody.addShape(wheelLBShape) this.wheelLBBody.position.set(-2, 0, 2) //this.physics.world.addBody(this.wheelLBBody) this.partIds.push(this.wheelLBBody.id) const wheelRBShape = new CANNON.Sphere(0.4) this.wheelRBBody = new CANNON.Body({ mass: 0, material: this.physics.wheelMaterial, }) this.wheelRBBody.addShape(wheelRBShape) this.wheelRBBody.position.set(2, 0, 2) //this.physics.world.addBody(this.wheelRBBody) this.partIds.push(this.wheelRBBody.id) //delay added to stop collisions occurring when objects being created setTimeout(() => { this.physics.world.addBody(this.frameBody) this.physics.world.addBody(this.wheelLFBody) this.physics.world.addBody(this.wheelRFBody) this.physics.world.addBody(this.wheelLBBody) this.physics.world.addBody(this.wheelRBBody) this.enabled = true }, 1000) } updateTargets(data: any) { this.screenName = data.sn if (this.lastScreenName !== this.screenName) { //changed this.annotationDiv.innerHTML = this.screenName this.lastScreenName = this.screenName } this.targetPosFrame.set(data.p.x, data.p.y, data.p.z) this.targetPosTurret.set(data.tp.x, data.tp.y, data.tp.z) this.targetPosWheelLF.set(data.w[0].p.x, data.w[0].p.y, data.w[0].p.z) this.targetPosWheelRF.set(data.w[1].p.x, data.w[1].p.y, data.w[1].p.z) this.targetPosWheelLB.set(data.w[2].p.x, data.w[2].p.y, data.w[2].p.z) this.targetPosWheelRB.set(data.w[3].p.x, data.w[3].p.y, data.w[3].p.z) this.frameMesh.quaternion.slerp( new THREE.Quaternion(data.q._x, data.q._y, data.q._z, data.q._w), 0.2 ) this.turretMesh.quaternion.slerp( new THREE.Quaternion(data.tq._x, data.tq._y, data.tq._z, data.tq._w), 0.2 //faster ) this.wheelLFMesh.quaternion.slerp( new THREE.Quaternion( data.w[0].q._x, data.w[0].q._y, data.w[0].q._z, data.w[0].q._w ), 0.2 ) this.wheelRFMesh.quaternion.slerp( new THREE.Quaternion( data.w[1].q._x, data.w[1].q._y, data.w[1].q._z, data.w[1].q._w ), 0.2 ) this.wheelLBMesh.quaternion.slerp( new THREE.Quaternion( data.w[2].q._x, data.w[2].q._y, data.w[2].q._z, data.w[2].q._w ), 0.2 ) this.wheelRBMesh.quaternion.slerp( new THREE.Quaternion( data.w[3].q._x, data.w[3].q._y, data.w[3].q._z, data.w[3].q._w ), 0.2 ) for (let i = 0; i < 3; i++) { if (data.b[i].c > this.lastBulletCounter[i]) { this.lastBulletCounter[i] = data.b[i].c if (this.shootSound.isPlaying) { this.shootSound.stop() } this.shootSound.play() //console.log("player shoot sound") } this.bulletMesh[i].position.set( data.b[i].p.x, data.b[i].p.y, data.b[i].p.z ) } this.carSound.setPlaybackRate(Math.abs(data.v / 50) + Math.random() / 9) this.enabled = data.e } update() { this.frameMesh.position.lerp(this.targetPosFrame, 0.2) this.turretMesh.position.lerp(this.targetPosTurret, 0.2) this.wheelLFMesh.position.lerp(this.targetPosWheelLF, 0.2) this.wheelRFMesh.position.lerp(this.targetPosWheelRF, 0.2) this.wheelLBMesh.position.lerp(this.targetPosWheelLB, 0.2) this.wheelRBMesh.position.lerp(this.targetPosWheelRB, 0.2) this.frameBody.position.set( this.frameMesh.position.x, this.frameMesh.position.y, this.frameMesh.position.z ) this.frameBody.quaternion.set( this.frameMesh.quaternion.x, this.frameMesh.quaternion.y, this.frameMesh.quaternion.z, this.frameMesh.quaternion.w ) this.wheelLFBody.position.set( this.wheelLFMesh.position.x, this.wheelLFMesh.position.y, this.wheelLFMesh.position.z ) this.wheelLFBody.quaternion.set( this.wheelLFMesh.quaternion.x, this.wheelLFMesh.quaternion.y, this.wheelLFMesh.quaternion.z, this.wheelLFMesh.quaternion.w ) this.wheelRFBody.position.set( this.wheelRFMesh.position.x, this.wheelRFMesh.position.y, this.wheelRFMesh.position.z ) this.wheelRFBody.quaternion.set( this.wheelRFMesh.quaternion.x, this.wheelRFMesh.quaternion.y, this.wheelRFMesh.quaternion.z, this.wheelRFMesh.quaternion.w ) this.wheelLBBody.position.set( this.wheelLBMesh.position.x, this.wheelLBMesh.position.y, this.wheelLBMesh.position.z ) this.wheelLBBody.quaternion.set( this.wheelLBMesh.quaternion.x, this.wheelLBMesh.quaternion.y, this.wheelLBMesh.quaternion.z, this.wheelLBMesh.quaternion.w ) this.wheelRBBody.position.set( this.wheelRBMesh.position.x, this.wheelRBMesh.position.y, this.wheelRBMesh.position.z ) this.wheelRBBody.quaternion.set( this.wheelRBMesh.quaternion.x, this.wheelRBMesh.quaternion.y, this.wheelRBMesh.quaternion.z, this.wheelRBMesh.quaternion.w ) } dispose() { for (let i = 0; i < 3; i++) { ;(this.bulletMesh[i].material as THREE.MeshBasicMaterial).dispose() this.lensflares[i].dispose() this.bulletMesh[i].geometry.dispose() this.scene.remove(this.bulletMesh[i]) } this.scene.remove(this.wheelLFMesh) this.scene.remove(this.wheelRFMesh) this.scene.remove(this.wheelLBMesh) this.scene.remove(this.wheelRBMesh) this.scene.remove(this.turretPivot) this.scene.remove(this.turretMesh) this.scene.remove(this.frameMesh) this.physics.world.removeBody(this.wheelLFBody) this.physics.world.removeBody(this.wheelRFBody) this.physics.world.removeBody(this.wheelLBBody) this.physics.world.removeBody(this.wheelRBBody) this.physics.world.removeBody(this.frameBody) this.annotationDiv.remove() // work in progress //console.log('scene object count = ' + this.scene.children.length) //this.wheelLFMesh.traverse((child: THREE.Object3D) => { // if ((child as THREE.Group).isGroup) { // console.log('here a') // child.traverse((child: THREE.Object3D) => { // if ((child as THREE.Mesh).isMesh) { // console.log('here b') // ;( // (child as THREE.Mesh) // .material as THREE.MeshBasicMaterial // ).dispose() // ;(child as THREE.Mesh).geometry.dispose() // } // }) // } // if ((child as THREE.Mesh).isMesh) { // //console.log('here c') // ;( // (child as THREE.Mesh).material as THREE.MeshBasicMaterial // ).dispose() // ;(child as THREE.Mesh).geometry.dispose() // } //}) } }
0
0.751956
1
0.751956
game-dev
MEDIA
0.662439
game-dev,web-frontend
0.933239
1
0.933239
Squalr/Squally
1,126
Source/Objects/Platformer/Traps/MetalSpikes/MetalSpikesGenericPreview.cpp
#include "MetalSpikesGenericPreview.h" #include "cocos/2d/CCActionEase.h" #include "cocos/2d/CCSprite.h" #include "Engine/Animations/SmartAnimationSequenceNode.h" #include "Resources/ObjectResources.h" using namespace cocos2d; MetalSpikesGenericPreview* MetalSpikesGenericPreview::create() { MetalSpikesGenericPreview* instance = new MetalSpikesGenericPreview(); instance->autorelease(); return instance; } MetalSpikesGenericPreview::MetalSpikesGenericPreview() { this->previewSpikes = SmartAnimationSequenceNode::create(ObjectResources::Traps_MetalSpikes_Spikes_0000); this->previewSpikes->setScale(0.4f); this->previewNode->addChild(this->previewSpikes); } MetalSpikesGenericPreview::~MetalSpikesGenericPreview() { } HackablePreview* MetalSpikesGenericPreview::clone() { return MetalSpikesGenericPreview::create(); } void MetalSpikesGenericPreview::onEnter() { super::onEnter(); this->previewSpikes->playAnimationAndReverseRepeat(ObjectResources::Traps_MetalSpikes_Spikes_0000, 0.025f, 1.5f, 0.025f, 0.025f); } void MetalSpikesGenericPreview::initializePositions() { super::initializePositions(); }
0
0.572818
1
0.572818
game-dev
MEDIA
0.726202
game-dev
0.728451
1
0.728451
Xiao-MoMi/craft-engine
3,506
core/src/main/java/net/momirealms/craftengine/core/plugin/context/number/GaussianNumberProvider.java
package net.momirealms.craftengine.core.plugin.context.number; import net.momirealms.craftengine.core.plugin.context.Context; import net.momirealms.craftengine.core.util.Key; import net.momirealms.craftengine.core.util.MiscUtils; import net.momirealms.craftengine.core.util.ResourceConfigUtils; import java.util.Map; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class GaussianNumberProvider implements NumberProvider { public static final Factory FACTORY = new Factory(); private final double min; private final double max; private final double mean; private final double stdDev; private final int maxAttempts; public GaussianNumberProvider(double min, double max, double mean, double stdDev, int maxAttempts) { this.min = min; this.max = max; this.mean = mean; this.stdDev = stdDev; this.maxAttempts = maxAttempts; validateParameters(); } private void validateParameters() { if (this.min >= this.max) { throw new IllegalArgumentException("min must be less than max"); } if (this.stdDev <= 0) { throw new IllegalArgumentException("std-dev must be greater than 0"); } if (this.maxAttempts <= 0) { throw new IllegalArgumentException("max-attempts must be greater than 0"); } } @Override public float getFloat(Context context) { return (float) getDouble(context); } @Override public double getDouble(Context context) { Random random = ThreadLocalRandom.current(); int attempts = 0; while (attempts < maxAttempts) { double value = random.nextGaussian() * stdDev + mean; if (value >= min && value <= max) { return value; } attempts++; } return MiscUtils.clamp(this.mean, this.min, this.max); } @Override public Key type() { return NumberProviders.GAUSSIAN; } public double min() { return min; } public double max() { return max; } public int maxAttempts() { return maxAttempts; } public double mean() { return mean; } public double stdDev() { return stdDev; } public static class Factory implements NumberProviderFactory { @Override public NumberProvider create(Map<String, Object> arguments) { double min = ResourceConfigUtils.getAsDouble(ResourceConfigUtils.requireNonNullOrThrow(arguments.get("min"), "warning.config.number.gaussian.missing_min"), "min"); double max = ResourceConfigUtils.getAsDouble(ResourceConfigUtils.requireNonNullOrThrow(arguments.get("max"), "warning.config.number.gaussian.missing_max"), "max"); double mean = ResourceConfigUtils.getAsDouble(arguments.getOrDefault("mean", (min + max) / 2.0), "mean"); double stdDev = ResourceConfigUtils.getAsDouble(arguments.getOrDefault("std-dev", (max - min) / 6.0), "std-dev"); int maxAttempts = ResourceConfigUtils.getAsInt(arguments.getOrDefault("max-attempts", 128), "max-attempts"); return new GaussianNumberProvider(min, max, mean, stdDev, maxAttempts); } } @Override public String toString() { return String.format("GaussianNumberProvider{min=%.2f, max=%.2f, mean=%.2f, stdDev=%.2f, maxAttempts=%d}", min, max, mean, stdDev, maxAttempts); } }
0
0.974018
1
0.974018
game-dev
MEDIA
0.538787
game-dev
0.879617
1
0.879617
fallahn/crogine
68,230
android/BulletDroid/src/BulletDynamics/Featherstone/btMultiBody.cpp
/* * PURPOSE: * Class representing an articulated rigid body. Stores the body's * current state, allows forces and torques to be set, handles * timestepping and implements Featherstone's algorithm. * * COPYRIGHT: * Copyright (C) Stephen Thompson, <stephen@solarflare.org.uk>, 2011-2013 * Portions written By Erwin Coumans: connection to LCP solver, various multibody constraints, replacing Eigen math library by Bullet LinearMath and a dedicated 6x6 matrix inverse (solveImatrix) * Portions written By Jakub Stepien: support for multi-DOF constraints, introduction of spatial algebra and several other improvements 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 "btMultiBody.h" #include "btMultiBodyLink.h" #include "btMultiBodyLinkCollider.h" #include "btMultiBodyJointFeedback.h" #include "LinearMath/btTransformUtil.h" #include "LinearMath/btSerializer.h" //#include "Bullet3Common/b3Logging.h" // #define INCLUDE_GYRO_TERM ///todo: determine if we need these options. If so, make a proper API, otherwise delete those globals bool gJointFeedbackInWorldSpace = false; bool gJointFeedbackInJointFrame = false; namespace { const btScalar SLEEP_EPSILON = btScalar(0.05); // this is a squared velocity (m^2 s^-2) const btScalar SLEEP_TIMEOUT = btScalar(2); // in seconds } namespace { void SpatialTransform(const btMatrix3x3 &rotation_matrix, // rotates vectors in 'from' frame to vectors in 'to' frame const btVector3 &displacement, // vector from origin of 'from' frame to origin of 'to' frame, in 'to' coordinates const btVector3 &top_in, // top part of input vector const btVector3 &bottom_in, // bottom part of input vector btVector3 &top_out, // top part of output vector btVector3 &bottom_out) // bottom part of output vector { top_out = rotation_matrix * top_in; bottom_out = -displacement.cross(top_out) + rotation_matrix * bottom_in; } #if 0 void InverseSpatialTransform(const btMatrix3x3 &rotation_matrix, const btVector3 &displacement, const btVector3 &top_in, const btVector3 &bottom_in, btVector3 &top_out, btVector3 &bottom_out) { top_out = rotation_matrix.transpose() * top_in; bottom_out = rotation_matrix.transpose() * (bottom_in + displacement.cross(top_in)); } btScalar SpatialDotProduct(const btVector3 &a_top, const btVector3 &a_bottom, const btVector3 &b_top, const btVector3 &b_bottom) { return a_bottom.dot(b_top) + a_top.dot(b_bottom); } void SpatialCrossProduct(const btVector3 &a_top, const btVector3 &a_bottom, const btVector3 &b_top, const btVector3 &b_bottom, btVector3 &top_out, btVector3 &bottom_out) { top_out = a_top.cross(b_top); bottom_out = a_bottom.cross(b_top) + a_top.cross(b_bottom); } #endif } // // Implementation of class btMultiBody // btMultiBody::btMultiBody(int n_links, btScalar mass, const btVector3 &inertia, bool fixedBase, bool canSleep, bool /*deprecatedUseMultiDof*/) : m_baseCollider(0), m_baseName(0), m_basePos(0,0,0), m_baseQuat(0, 0, 0, 1), m_baseMass(mass), m_baseInertia(inertia), m_fixedBase(fixedBase), m_awake(true), m_canSleep(canSleep), m_sleepTimer(0), m_userObjectPointer(0), m_userIndex2(-1), m_userIndex(-1), m_linearDamping(0.04f), m_angularDamping(0.04f), m_useGyroTerm(true), m_maxAppliedImpulse(1000.f), m_maxCoordinateVelocity(100.f), m_hasSelfCollision(true), __posUpdated(false), m_dofCount(0), m_posVarCnt(0), m_useRK4(false), m_useGlobalVelocities(false), m_internalNeedsJointFeedback(false) { m_cachedInertiaTopLeft.setValue(0,0,0,0,0,0,0,0,0); m_cachedInertiaTopRight.setValue(0,0,0,0,0,0,0,0,0); m_cachedInertiaLowerLeft.setValue(0,0,0,0,0,0,0,0,0); m_cachedInertiaLowerRight.setValue(0,0,0,0,0,0,0,0,0); m_cachedInertiaValid=false; m_links.resize(n_links); m_matrixBuf.resize(n_links + 1); m_baseForce.setValue(0, 0, 0); m_baseTorque.setValue(0, 0, 0); } btMultiBody::~btMultiBody() { } void btMultiBody::setupFixed(int i, btScalar mass, const btVector3 &inertia, int parent, const btQuaternion &rotParentToThis, const btVector3 &parentComToThisPivotOffset, const btVector3 &thisPivotToThisComOffset, bool /*deprecatedDisableParentCollision*/) { m_links[i].m_mass = mass; m_links[i].m_inertiaLocal = inertia; m_links[i].m_parent = parent; m_links[i].m_zeroRotParentToThis = rotParentToThis; m_links[i].m_dVector = thisPivotToThisComOffset; m_links[i].m_eVector = parentComToThisPivotOffset; m_links[i].m_jointType = btMultibodyLink::eFixed; m_links[i].m_dofCount = 0; m_links[i].m_posVarCount = 0; m_links[i].m_flags |=BT_MULTIBODYLINKFLAGS_DISABLE_PARENT_COLLISION; m_links[i].updateCacheMultiDof(); updateLinksDofOffsets(); } void btMultiBody::setupPrismatic(int i, btScalar mass, const btVector3 &inertia, int parent, const btQuaternion &rotParentToThis, const btVector3 &jointAxis, const btVector3 &parentComToThisPivotOffset, const btVector3 &thisPivotToThisComOffset, bool disableParentCollision) { m_dofCount += 1; m_posVarCnt += 1; m_links[i].m_mass = mass; m_links[i].m_inertiaLocal = inertia; m_links[i].m_parent = parent; m_links[i].m_zeroRotParentToThis = rotParentToThis; m_links[i].setAxisTop(0, 0., 0., 0.); m_links[i].setAxisBottom(0, jointAxis); m_links[i].m_eVector = parentComToThisPivotOffset; m_links[i].m_dVector = thisPivotToThisComOffset; m_links[i].m_cachedRotParentToThis = rotParentToThis; m_links[i].m_jointType = btMultibodyLink::ePrismatic; m_links[i].m_dofCount = 1; m_links[i].m_posVarCount = 1; m_links[i].m_jointPos[0] = 0.f; m_links[i].m_jointTorque[0] = 0.f; if (disableParentCollision) m_links[i].m_flags |=BT_MULTIBODYLINKFLAGS_DISABLE_PARENT_COLLISION; // m_links[i].updateCacheMultiDof(); updateLinksDofOffsets(); } void btMultiBody::setupRevolute(int i, btScalar mass, const btVector3 &inertia, int parent, const btQuaternion &rotParentToThis, const btVector3 &jointAxis, const btVector3 &parentComToThisPivotOffset, const btVector3 &thisPivotToThisComOffset, bool disableParentCollision) { m_dofCount += 1; m_posVarCnt += 1; m_links[i].m_mass = mass; m_links[i].m_inertiaLocal = inertia; m_links[i].m_parent = parent; m_links[i].m_zeroRotParentToThis = rotParentToThis; m_links[i].setAxisTop(0, jointAxis); m_links[i].setAxisBottom(0, jointAxis.cross(thisPivotToThisComOffset)); m_links[i].m_dVector = thisPivotToThisComOffset; m_links[i].m_eVector = parentComToThisPivotOffset; m_links[i].m_jointType = btMultibodyLink::eRevolute; m_links[i].m_dofCount = 1; m_links[i].m_posVarCount = 1; m_links[i].m_jointPos[0] = 0.f; m_links[i].m_jointTorque[0] = 0.f; if (disableParentCollision) m_links[i].m_flags |=BT_MULTIBODYLINKFLAGS_DISABLE_PARENT_COLLISION; // m_links[i].updateCacheMultiDof(); // updateLinksDofOffsets(); } void btMultiBody::setupSpherical(int i, btScalar mass, const btVector3 &inertia, int parent, const btQuaternion &rotParentToThis, const btVector3 &parentComToThisPivotOffset, const btVector3 &thisPivotToThisComOffset, bool disableParentCollision) { m_dofCount += 3; m_posVarCnt += 4; m_links[i].m_mass = mass; m_links[i].m_inertiaLocal = inertia; m_links[i].m_parent = parent; m_links[i].m_zeroRotParentToThis = rotParentToThis; m_links[i].m_dVector = thisPivotToThisComOffset; m_links[i].m_eVector = parentComToThisPivotOffset; m_links[i].m_jointType = btMultibodyLink::eSpherical; m_links[i].m_dofCount = 3; m_links[i].m_posVarCount = 4; m_links[i].setAxisTop(0, 1.f, 0.f, 0.f); m_links[i].setAxisTop(1, 0.f, 1.f, 0.f); m_links[i].setAxisTop(2, 0.f, 0.f, 1.f); m_links[i].setAxisBottom(0, m_links[i].getAxisTop(0).cross(thisPivotToThisComOffset)); m_links[i].setAxisBottom(1, m_links[i].getAxisTop(1).cross(thisPivotToThisComOffset)); m_links[i].setAxisBottom(2, m_links[i].getAxisTop(2).cross(thisPivotToThisComOffset)); m_links[i].m_jointPos[0] = m_links[i].m_jointPos[1] = m_links[i].m_jointPos[2] = 0.f; m_links[i].m_jointPos[3] = 1.f; m_links[i].m_jointTorque[0] = m_links[i].m_jointTorque[1] = m_links[i].m_jointTorque[2] = 0.f; if (disableParentCollision) m_links[i].m_flags |=BT_MULTIBODYLINKFLAGS_DISABLE_PARENT_COLLISION; // m_links[i].updateCacheMultiDof(); // updateLinksDofOffsets(); } void btMultiBody::setupPlanar(int i, btScalar mass, const btVector3 &inertia, int parent, const btQuaternion &rotParentToThis, const btVector3 &rotationAxis, const btVector3 &parentComToThisComOffset, bool disableParentCollision) { m_dofCount += 3; m_posVarCnt += 3; m_links[i].m_mass = mass; m_links[i].m_inertiaLocal = inertia; m_links[i].m_parent = parent; m_links[i].m_zeroRotParentToThis = rotParentToThis; m_links[i].m_dVector.setZero(); m_links[i].m_eVector = parentComToThisComOffset; // btVector3 vecNonParallelToRotAxis(1, 0, 0); if(rotationAxis.normalized().dot(vecNonParallelToRotAxis) > 0.999) vecNonParallelToRotAxis.setValue(0, 1, 0); // m_links[i].m_jointType = btMultibodyLink::ePlanar; m_links[i].m_dofCount = 3; m_links[i].m_posVarCount = 3; btVector3 n=rotationAxis.normalized(); m_links[i].setAxisTop(0, n[0],n[1],n[2]); m_links[i].setAxisTop(1,0,0,0); m_links[i].setAxisTop(2,0,0,0); m_links[i].setAxisBottom(0,0,0,0); btVector3 cr = m_links[i].getAxisTop(0).cross(vecNonParallelToRotAxis); m_links[i].setAxisBottom(1,cr[0],cr[1],cr[2]); cr = m_links[i].getAxisBottom(1).cross(m_links[i].getAxisTop(0)); m_links[i].setAxisBottom(2,cr[0],cr[1],cr[2]); m_links[i].m_jointPos[0] = m_links[i].m_jointPos[1] = m_links[i].m_jointPos[2] = 0.f; m_links[i].m_jointTorque[0] = m_links[i].m_jointTorque[1] = m_links[i].m_jointTorque[2] = 0.f; if (disableParentCollision) m_links[i].m_flags |=BT_MULTIBODYLINKFLAGS_DISABLE_PARENT_COLLISION; // m_links[i].updateCacheMultiDof(); // updateLinksDofOffsets(); } void btMultiBody::finalizeMultiDof() { m_deltaV.resize(0); m_deltaV.resize(6 + m_dofCount); m_realBuf.resize(6 + m_dofCount + m_dofCount*m_dofCount + 6 + m_dofCount); //m_dofCount for joint-space vels + m_dofCount^2 for "D" matrices + delta-pos vector (6 base "vels" + joint "vels") m_vectorBuf.resize(2 * m_dofCount); //two 3-vectors (i.e. one six-vector) for each system dof ("h" matrices) updateLinksDofOffsets(); } int btMultiBody::getParent(int i) const { return m_links[i].m_parent; } btScalar btMultiBody::getLinkMass(int i) const { return m_links[i].m_mass; } const btVector3 & btMultiBody::getLinkInertia(int i) const { return m_links[i].m_inertiaLocal; } btScalar btMultiBody::getJointPos(int i) const { return m_links[i].m_jointPos[0]; } btScalar btMultiBody::getJointVel(int i) const { return m_realBuf[6 + m_links[i].m_dofOffset]; } btScalar * btMultiBody::getJointPosMultiDof(int i) { return &m_links[i].m_jointPos[0]; } btScalar * btMultiBody::getJointVelMultiDof(int i) { return &m_realBuf[6 + m_links[i].m_dofOffset]; } const btScalar * btMultiBody::getJointPosMultiDof(int i) const { return &m_links[i].m_jointPos[0]; } const btScalar * btMultiBody::getJointVelMultiDof(int i) const { return &m_realBuf[6 + m_links[i].m_dofOffset]; } void btMultiBody::setJointPos(int i, btScalar q) { m_links[i].m_jointPos[0] = q; m_links[i].updateCacheMultiDof(); } void btMultiBody::setJointPosMultiDof(int i, btScalar *q) { for(int pos = 0; pos < m_links[i].m_posVarCount; ++pos) m_links[i].m_jointPos[pos] = q[pos]; m_links[i].updateCacheMultiDof(); } void btMultiBody::setJointVel(int i, btScalar qdot) { m_realBuf[6 + m_links[i].m_dofOffset] = qdot; } void btMultiBody::setJointVelMultiDof(int i, btScalar *qdot) { for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) m_realBuf[6 + m_links[i].m_dofOffset + dof] = qdot[dof]; } const btVector3 & btMultiBody::getRVector(int i) const { return m_links[i].m_cachedRVector; } const btQuaternion & btMultiBody::getParentToLocalRot(int i) const { return m_links[i].m_cachedRotParentToThis; } btVector3 btMultiBody::localPosToWorld(int i, const btVector3 &local_pos) const { btAssert(i>=-1); btAssert(i<m_links.size()); if ((i<-1) || (i>=m_links.size())) { return btVector3(SIMD_INFINITY,SIMD_INFINITY,SIMD_INFINITY); } btVector3 result = local_pos; while (i != -1) { // 'result' is in frame i. transform it to frame parent(i) result += getRVector(i); result = quatRotate(getParentToLocalRot(i).inverse(),result); i = getParent(i); } // 'result' is now in the base frame. transform it to world frame result = quatRotate(getWorldToBaseRot().inverse() ,result); result += getBasePos(); return result; } btVector3 btMultiBody::worldPosToLocal(int i, const btVector3 &world_pos) const { btAssert(i>=-1); btAssert(i<m_links.size()); if ((i<-1) || (i>=m_links.size())) { return btVector3(SIMD_INFINITY,SIMD_INFINITY,SIMD_INFINITY); } if (i == -1) { // world to base return quatRotate(getWorldToBaseRot(),(world_pos - getBasePos())); } else { // find position in parent frame, then transform to current frame return quatRotate(getParentToLocalRot(i),worldPosToLocal(getParent(i), world_pos)) - getRVector(i); } } btVector3 btMultiBody::localDirToWorld(int i, const btVector3 &local_dir) const { btAssert(i>=-1); btAssert(i<m_links.size()); if ((i<-1) || (i>=m_links.size())) { return btVector3(SIMD_INFINITY,SIMD_INFINITY,SIMD_INFINITY); } btVector3 result = local_dir; while (i != -1) { result = quatRotate(getParentToLocalRot(i).inverse() , result); i = getParent(i); } result = quatRotate(getWorldToBaseRot().inverse() , result); return result; } btVector3 btMultiBody::worldDirToLocal(int i, const btVector3 &world_dir) const { btAssert(i>=-1); btAssert(i<m_links.size()); if ((i<-1) || (i>=m_links.size())) { return btVector3(SIMD_INFINITY,SIMD_INFINITY,SIMD_INFINITY); } if (i == -1) { return quatRotate(getWorldToBaseRot(), world_dir); } else { return quatRotate(getParentToLocalRot(i) ,worldDirToLocal(getParent(i), world_dir)); } } btMatrix3x3 btMultiBody::localFrameToWorld(int i, const btMatrix3x3 &local_frame) const { btMatrix3x3 result = local_frame; btVector3 frameInWorld0 = localDirToWorld(i, local_frame.getColumn(0)); btVector3 frameInWorld1 = localDirToWorld(i, local_frame.getColumn(1)); btVector3 frameInWorld2 = localDirToWorld(i, local_frame.getColumn(2)); result.setValue(frameInWorld0[0], frameInWorld1[0], frameInWorld2[0], frameInWorld0[1], frameInWorld1[1], frameInWorld2[1], frameInWorld0[2], frameInWorld1[2], frameInWorld2[2]); return result; } void btMultiBody::compTreeLinkVelocities(btVector3 *omega, btVector3 *vel) const { int num_links = getNumLinks(); // Calculates the velocities of each link (and the base) in its local frame omega[0] = quatRotate(m_baseQuat ,getBaseOmega()); vel[0] = quatRotate(m_baseQuat ,getBaseVel()); for (int i = 0; i < num_links; ++i) { const int parent = m_links[i].m_parent; // transform parent vel into this frame, store in omega[i+1], vel[i+1] SpatialTransform(btMatrix3x3(m_links[i].m_cachedRotParentToThis), m_links[i].m_cachedRVector, omega[parent+1], vel[parent+1], omega[i+1], vel[i+1]); // now add qidot * shat_i omega[i+1] += getJointVel(i) * m_links[i].getAxisTop(0); vel[i+1] += getJointVel(i) * m_links[i].getAxisBottom(0); } } btScalar btMultiBody::getKineticEnergy() const { int num_links = getNumLinks(); // TODO: would be better not to allocate memory here btAlignedObjectArray<btVector3> omega;omega.resize(num_links+1); btAlignedObjectArray<btVector3> vel;vel.resize(num_links+1); compTreeLinkVelocities(&omega[0], &vel[0]); // we will do the factor of 0.5 at the end btScalar result = m_baseMass * vel[0].dot(vel[0]); result += omega[0].dot(m_baseInertia * omega[0]); for (int i = 0; i < num_links; ++i) { result += m_links[i].m_mass * vel[i+1].dot(vel[i+1]); result += omega[i+1].dot(m_links[i].m_inertiaLocal * omega[i+1]); } return 0.5f * result; } btVector3 btMultiBody::getAngularMomentum() const { int num_links = getNumLinks(); // TODO: would be better not to allocate memory here btAlignedObjectArray<btVector3> omega;omega.resize(num_links+1); btAlignedObjectArray<btVector3> vel;vel.resize(num_links+1); btAlignedObjectArray<btQuaternion> rot_from_world;rot_from_world.resize(num_links+1); compTreeLinkVelocities(&omega[0], &vel[0]); rot_from_world[0] = m_baseQuat; btVector3 result = quatRotate(rot_from_world[0].inverse() , (m_baseInertia * omega[0])); for (int i = 0; i < num_links; ++i) { rot_from_world[i+1] = m_links[i].m_cachedRotParentToThis * rot_from_world[m_links[i].m_parent+1]; result += (quatRotate(rot_from_world[i+1].inverse() , (m_links[i].m_inertiaLocal * omega[i+1]))); } return result; } void btMultiBody::clearConstraintForces() { m_baseConstraintForce.setValue(0, 0, 0); m_baseConstraintTorque.setValue(0, 0, 0); for (int i = 0; i < getNumLinks(); ++i) { m_links[i].m_appliedConstraintForce.setValue(0, 0, 0); m_links[i].m_appliedConstraintTorque.setValue(0, 0, 0); } } void btMultiBody::clearForcesAndTorques() { m_baseForce.setValue(0, 0, 0); m_baseTorque.setValue(0, 0, 0); for (int i = 0; i < getNumLinks(); ++i) { m_links[i].m_appliedForce.setValue(0, 0, 0); m_links[i].m_appliedTorque.setValue(0, 0, 0); m_links[i].m_jointTorque[0] = m_links[i].m_jointTorque[1] = m_links[i].m_jointTorque[2] = m_links[i].m_jointTorque[3] = m_links[i].m_jointTorque[4] = m_links[i].m_jointTorque[5] = 0.f; } } void btMultiBody::clearVelocities() { for (int i = 0; i < 6 + getNumDofs(); ++i) { m_realBuf[i] = 0.f; } } void btMultiBody::addLinkForce(int i, const btVector3 &f) { m_links[i].m_appliedForce += f; } void btMultiBody::addLinkTorque(int i, const btVector3 &t) { m_links[i].m_appliedTorque += t; } void btMultiBody::addLinkConstraintForce(int i, const btVector3 &f) { m_links[i].m_appliedConstraintForce += f; } void btMultiBody::addLinkConstraintTorque(int i, const btVector3 &t) { m_links[i].m_appliedConstraintTorque += t; } void btMultiBody::addJointTorque(int i, btScalar Q) { m_links[i].m_jointTorque[0] += Q; } void btMultiBody::addJointTorqueMultiDof(int i, int dof, btScalar Q) { m_links[i].m_jointTorque[dof] += Q; } void btMultiBody::addJointTorqueMultiDof(int i, const btScalar *Q) { for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) m_links[i].m_jointTorque[dof] = Q[dof]; } const btVector3 & btMultiBody::getLinkForce(int i) const { return m_links[i].m_appliedForce; } const btVector3 & btMultiBody::getLinkTorque(int i) const { return m_links[i].m_appliedTorque; } btScalar btMultiBody::getJointTorque(int i) const { return m_links[i].m_jointTorque[0]; } btScalar * btMultiBody::getJointTorqueMultiDof(int i) { return &m_links[i].m_jointTorque[0]; } inline btMatrix3x3 outerProduct(const btVector3& v0, const btVector3& v1) //renamed it from vecMulVecTranspose (http://en.wikipedia.org/wiki/Outer_product); maybe it should be moved to btVector3 like dot and cross? { btVector3 row0 = btVector3( v0.x() * v1.x(), v0.x() * v1.y(), v0.x() * v1.z()); btVector3 row1 = btVector3( v0.y() * v1.x(), v0.y() * v1.y(), v0.y() * v1.z()); btVector3 row2 = btVector3( v0.z() * v1.x(), v0.z() * v1.y(), v0.z() * v1.z()); btMatrix3x3 m(row0[0],row0[1],row0[2], row1[0],row1[1],row1[2], row2[0],row2[1],row2[2]); return m; } #define vecMulVecTranspose(v0, v1Transposed) outerProduct(v0, v1Transposed) // void btMultiBody::computeAccelerationsArticulatedBodyAlgorithmMultiDof(btScalar dt, btAlignedObjectArray<btScalar> &scratch_r, btAlignedObjectArray<btVector3> &scratch_v, btAlignedObjectArray<btMatrix3x3> &scratch_m, bool isConstraintPass) { // Implement Featherstone's algorithm to calculate joint accelerations (q_double_dot) // and the base linear & angular accelerations. // We apply damping forces in this routine as well as any external forces specified by the // caller (via addBaseForce etc). // output should point to an array of 6 + num_links reals. // Format is: 3 angular accelerations (in world frame), 3 linear accelerations (in world frame), // num_links joint acceleration values. // We added support for multi degree of freedom (multi dof) joints. // In addition we also can compute the joint reaction forces. This is performed in a second pass, // so that we can include the effect of the constraint solver forces (computed in the PGS LCP solver) m_internalNeedsJointFeedback = false; int num_links = getNumLinks(); const btScalar DAMPING_K1_LINEAR = m_linearDamping; const btScalar DAMPING_K2_LINEAR = m_linearDamping; const btScalar DAMPING_K1_ANGULAR = m_angularDamping; const btScalar DAMPING_K2_ANGULAR= m_angularDamping; btVector3 base_vel = getBaseVel(); btVector3 base_omega = getBaseOmega(); // Temporary matrices/vectors -- use scratch space from caller // so that we don't have to keep reallocating every frame scratch_r.resize(2*m_dofCount + 6); //multidof? ("Y"s use it and it is used to store qdd) => 2 x m_dofCount scratch_v.resize(8*num_links + 6); scratch_m.resize(4*num_links + 4); //btScalar * r_ptr = &scratch_r[0]; btScalar * output = &scratch_r[m_dofCount]; // "output" holds the q_double_dot results btVector3 * v_ptr = &scratch_v[0]; // vhat_i (top = angular, bottom = linear part) btSpatialMotionVector *spatVel = (btSpatialMotionVector *)v_ptr; v_ptr += num_links * 2 + 2; // // zhat_i^A btSpatialForceVector * zeroAccSpatFrc = (btSpatialForceVector *)v_ptr; v_ptr += num_links * 2 + 2; // // chat_i (note NOT defined for the base) btSpatialMotionVector * spatCoriolisAcc = (btSpatialMotionVector *)v_ptr; v_ptr += num_links * 2; // // Ihat_i^A. btSymmetricSpatialDyad * spatInertia = (btSymmetricSpatialDyad *)&scratch_m[num_links + 1]; // Cached 3x3 rotation matrices from parent frame to this frame. btMatrix3x3 * rot_from_parent = &m_matrixBuf[0]; btMatrix3x3 * rot_from_world = &scratch_m[0]; // hhat_i, ahat_i // hhat is NOT stored for the base (but ahat is) btSpatialForceVector * h = (btSpatialForceVector *)(m_dofCount > 0 ? &m_vectorBuf[0] : 0); btSpatialMotionVector * spatAcc = (btSpatialMotionVector *)v_ptr; v_ptr += num_links * 2 + 2; // // Y_i, invD_i btScalar * invD = m_dofCount > 0 ? &m_realBuf[6 + m_dofCount] : 0; btScalar * Y = &scratch_r[0]; // //aux variables btSpatialMotionVector spatJointVel; //spatial velocity due to the joint motion (i.e. without predecessors' influence) btScalar D[36]; //"D" matrix; it's dofxdof for each body so asingle 6x6 D matrix will do btScalar invD_times_Y[6]; //D^{-1} * Y [dofxdof x dofx1 = dofx1] <=> D^{-1} * u; better moved to buffers since it is recalced in calcAccelerationDeltasMultiDof; num_dof of btScalar would cover all bodies btSpatialMotionVector result; //holds results of the SolveImatrix op; it is a spatial motion vector (accel) btScalar Y_minus_hT_a[6]; //Y - h^{T} * a; it's dofx1 for each body so a single 6x1 temp is enough btSpatialForceVector spatForceVecTemps[6]; //6 temporary spatial force vectors btSpatialTransformationMatrix fromParent; //spatial transform from parent to child btSymmetricSpatialDyad dyadTemp; //inertia matrix temp btSpatialTransformationMatrix fromWorld; fromWorld.m_trnVec.setZero(); ///////////////// // ptr to the joint accel part of the output btScalar * joint_accel = output + 6; // Start of the algorithm proper. // First 'upward' loop. // Combines CompTreeLinkVelocities and InitTreeLinks from Mirtich. rot_from_parent[0] = btMatrix3x3(m_baseQuat); //m_baseQuat assumed to be alias!? //create the vector of spatial velocity of the base by transforming global-coor linear and angular velocities into base-local coordinates spatVel[0].setVector(rot_from_parent[0] * base_omega, rot_from_parent[0] * base_vel); if (m_fixedBase) { zeroAccSpatFrc[0].setZero(); } else { btVector3 baseForce = isConstraintPass? m_baseConstraintForce : m_baseForce; btVector3 baseTorque = isConstraintPass? m_baseConstraintTorque : m_baseTorque; //external forces zeroAccSpatFrc[0].setVector(-(rot_from_parent[0] * baseTorque), -(rot_from_parent[0] * baseForce)); //adding damping terms (only) btScalar linDampMult = 1., angDampMult = 1.; zeroAccSpatFrc[0].addVector(angDampMult * m_baseInertia * spatVel[0].getAngular() * (DAMPING_K1_ANGULAR + DAMPING_K2_ANGULAR * spatVel[0].getAngular().safeNorm()), linDampMult * m_baseMass * spatVel[0].getLinear() * (DAMPING_K1_LINEAR + DAMPING_K2_LINEAR * spatVel[0].getLinear().safeNorm())); // //p += vhat x Ihat vhat - done in a simpler way if (m_useGyroTerm) zeroAccSpatFrc[0].addAngular(spatVel[0].getAngular().cross(m_baseInertia * spatVel[0].getAngular())); // zeroAccSpatFrc[0].addLinear(m_baseMass * spatVel[0].getAngular().cross(spatVel[0].getLinear())); } //init the spatial AB inertia (it has the simple form thanks to choosing local body frames origins at their COMs) spatInertia[0].setMatrix( btMatrix3x3(0,0,0,0,0,0,0,0,0), // btMatrix3x3(m_baseMass, 0, 0, 0, m_baseMass, 0, 0, 0, m_baseMass), // btMatrix3x3(m_baseInertia[0], 0, 0, 0, m_baseInertia[1], 0, 0, 0, m_baseInertia[2]) ); rot_from_world[0] = rot_from_parent[0]; // for (int i = 0; i < num_links; ++i) { const int parent = m_links[i].m_parent; rot_from_parent[i+1] = btMatrix3x3(m_links[i].m_cachedRotParentToThis); rot_from_world[i+1] = rot_from_parent[i+1] * rot_from_world[parent+1]; fromParent.m_rotMat = rot_from_parent[i+1]; fromParent.m_trnVec = m_links[i].m_cachedRVector; fromWorld.m_rotMat = rot_from_world[i+1]; fromParent.transform(spatVel[parent+1], spatVel[i+1]); // now set vhat_i to its true value by doing // vhat_i += qidot * shat_i if(!m_useGlobalVelocities) { spatJointVel.setZero(); for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) spatJointVel += m_links[i].m_axes[dof] * getJointVelMultiDof(i)[dof]; // remember vhat_i is really vhat_p(i) (but in current frame) at this point => we need to add velocity across the inboard joint spatVel[i+1] += spatJointVel; // // vhat_i is vhat_p(i) transformed to local coors + the velocity across the i-th inboard joint //spatVel[i+1] = fromParent * spatVel[parent+1] + spatJointVel; } else { fromWorld.transformRotationOnly(m_links[i].m_absFrameTotVelocity, spatVel[i+1]); fromWorld.transformRotationOnly(m_links[i].m_absFrameLocVelocity, spatJointVel); } // we can now calculate chat_i spatVel[i+1].cross(spatJointVel, spatCoriolisAcc[i]); // calculate zhat_i^A // //external forces btVector3 linkAppliedForce = isConstraintPass? m_links[i].m_appliedConstraintForce : m_links[i].m_appliedForce; btVector3 linkAppliedTorque =isConstraintPass ? m_links[i].m_appliedConstraintTorque : m_links[i].m_appliedTorque; zeroAccSpatFrc[i+1].setVector(-(rot_from_world[i+1] * linkAppliedTorque), -(rot_from_world[i+1] * linkAppliedForce )); #if 0 { b3Printf("stepVelocitiesMultiDof zeroAccSpatFrc[%d] linear:%f,%f,%f, angular:%f,%f,%f", i+1, zeroAccSpatFrc[i+1].m_topVec[0], zeroAccSpatFrc[i+1].m_topVec[1], zeroAccSpatFrc[i+1].m_topVec[2], zeroAccSpatFrc[i+1].m_bottomVec[0], zeroAccSpatFrc[i+1].m_bottomVec[1], zeroAccSpatFrc[i+1].m_bottomVec[2]); } #endif // //adding damping terms (only) btScalar linDampMult = 1., angDampMult = 1.; zeroAccSpatFrc[i+1].addVector(angDampMult * m_links[i].m_inertiaLocal * spatVel[i+1].getAngular() * (DAMPING_K1_ANGULAR + DAMPING_K2_ANGULAR * spatVel[i+1].getAngular().safeNorm()), linDampMult * m_links[i].m_mass * spatVel[i+1].getLinear() * (DAMPING_K1_LINEAR + DAMPING_K2_LINEAR * spatVel[i+1].getLinear().safeNorm())); // calculate Ihat_i^A //init the spatial AB inertia (it has the simple form thanks to choosing local body frames origins at their COMs) spatInertia[i+1].setMatrix( btMatrix3x3(0,0,0,0,0,0,0,0,0), // btMatrix3x3(m_links[i].m_mass, 0, 0, 0, m_links[i].m_mass, 0, 0, 0, m_links[i].m_mass), // btMatrix3x3(m_links[i].m_inertiaLocal[0], 0, 0, 0, m_links[i].m_inertiaLocal[1], 0, 0, 0, m_links[i].m_inertiaLocal[2]) ); // //p += vhat x Ihat vhat - done in a simpler way if(m_useGyroTerm) zeroAccSpatFrc[i+1].addAngular(spatVel[i+1].getAngular().cross(m_links[i].m_inertiaLocal * spatVel[i+1].getAngular())); // zeroAccSpatFrc[i+1].addLinear(m_links[i].m_mass * spatVel[i+1].getAngular().cross(spatVel[i+1].getLinear())); //btVector3 temp = m_links[i].m_mass * spatVel[i+1].getAngular().cross(spatVel[i+1].getLinear()); ////clamp parent's omega //btScalar parOmegaMod = temp.length(); //btScalar parOmegaModMax = 1000; //if(parOmegaMod > parOmegaModMax) // temp *= parOmegaModMax / parOmegaMod; //zeroAccSpatFrc[i+1].addLinear(temp); //printf("|zeroAccSpatFrc[%d]| = %.4f\n", i+1, temp.length()); //temp = spatCoriolisAcc[i].getLinear(); //printf("|spatCoriolisAcc[%d]| = %.4f\n", i+1, temp.length()); //printf("w[%d] = [%.4f %.4f %.4f]\n", i, vel_top_angular[i+1].x(), vel_top_angular[i+1].y(), vel_top_angular[i+1].z()); //printf("v[%d] = [%.4f %.4f %.4f]\n", i, vel_bottom_linear[i+1].x(), vel_bottom_linear[i+1].y(), vel_bottom_linear[i+1].z()); //printf("c[%d] = [%.4f %.4f %.4f]\n", i, coriolis_bottom_linear[i].x(), coriolis_bottom_linear[i].y(), coriolis_bottom_linear[i].z()); } // 'Downward' loop. // (part of TreeForwardDynamics in Mirtich.) for (int i = num_links - 1; i >= 0; --i) { const int parent = m_links[i].m_parent; fromParent.m_rotMat = rot_from_parent[i+1]; fromParent.m_trnVec = m_links[i].m_cachedRVector; for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { btSpatialForceVector &hDof = h[m_links[i].m_dofOffset + dof]; // hDof = spatInertia[i+1] * m_links[i].m_axes[dof]; // Y[m_links[i].m_dofOffset + dof] = m_links[i].m_jointTorque[dof] - m_links[i].m_axes[dof].dot(zeroAccSpatFrc[i+1]) - spatCoriolisAcc[i].dot(hDof) ; } for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { btScalar *D_row = &D[dof * m_links[i].m_dofCount]; for(int dof2 = 0; dof2 < m_links[i].m_dofCount; ++dof2) { btSpatialForceVector &hDof2 = h[m_links[i].m_dofOffset + dof2]; D_row[dof2] = m_links[i].m_axes[dof].dot(hDof2); } } btScalar *invDi = &invD[m_links[i].m_dofOffset*m_links[i].m_dofOffset]; switch(m_links[i].m_jointType) { case btMultibodyLink::ePrismatic: case btMultibodyLink::eRevolute: { invDi[0] = 1.0f / D[0]; break; } case btMultibodyLink::eSpherical: case btMultibodyLink::ePlanar: { btMatrix3x3 D3x3; D3x3.setValue(D[0], D[1], D[2], D[3], D[4], D[5], D[6], D[7], D[8]); btMatrix3x3 invD3x3; invD3x3 = D3x3.inverse(); //unroll the loop? for(int row = 0; row < 3; ++row) { for(int col = 0; col < 3; ++col) { invDi[row * 3 + col] = invD3x3[row][col]; } } break; } default: { } } //determine h*D^{-1} for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { spatForceVecTemps[dof].setZero(); for(int dof2 = 0; dof2 < m_links[i].m_dofCount; ++dof2) { btSpatialForceVector &hDof2 = h[m_links[i].m_dofOffset + dof2]; // spatForceVecTemps[dof] += hDof2 * invDi[dof2 * m_links[i].m_dofCount + dof]; } } dyadTemp = spatInertia[i+1]; //determine (h*D^{-1}) * h^{T} for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { btSpatialForceVector &hDof = h[m_links[i].m_dofOffset + dof]; // dyadTemp -= symmetricSpatialOuterProduct(hDof, spatForceVecTemps[dof]); } fromParent.transformInverse(dyadTemp, spatInertia[parent+1], btSpatialTransformationMatrix::Add); for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { invD_times_Y[dof] = 0.f; for(int dof2 = 0; dof2 < m_links[i].m_dofCount; ++dof2) { invD_times_Y[dof] += invDi[dof * m_links[i].m_dofCount + dof2] * Y[m_links[i].m_dofOffset + dof2]; } } spatForceVecTemps[0] = zeroAccSpatFrc[i+1] + spatInertia[i+1] * spatCoriolisAcc[i]; for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { btSpatialForceVector &hDof = h[m_links[i].m_dofOffset + dof]; // spatForceVecTemps[0] += hDof * invD_times_Y[dof]; } fromParent.transformInverse(spatForceVecTemps[0], spatForceVecTemps[1]); zeroAccSpatFrc[parent+1] += spatForceVecTemps[1]; } // Second 'upward' loop // (part of TreeForwardDynamics in Mirtich) if (m_fixedBase) { spatAcc[0].setZero(); } else { if (num_links > 0) { m_cachedInertiaValid = true; m_cachedInertiaTopLeft = spatInertia[0].m_topLeftMat; m_cachedInertiaTopRight = spatInertia[0].m_topRightMat; m_cachedInertiaLowerLeft = spatInertia[0].m_bottomLeftMat; m_cachedInertiaLowerRight= spatInertia[0].m_topLeftMat.transpose(); } solveImatrix(zeroAccSpatFrc[0], result); spatAcc[0] = -result; } // now do the loop over the m_links for (int i = 0; i < num_links; ++i) { // qdd = D^{-1} * (Y - h^{T}*apar) = (S^{T}*I*S)^{-1} * (tau - S^{T}*I*cor - S^{T}*zeroAccFrc - S^{T}*I*apar) // a = apar + cor + Sqdd //or // qdd = D^{-1} * (Y - h^{T}*(apar+cor)) // a = apar + Sqdd const int parent = m_links[i].m_parent; fromParent.m_rotMat = rot_from_parent[i+1]; fromParent.m_trnVec = m_links[i].m_cachedRVector; fromParent.transform(spatAcc[parent+1], spatAcc[i+1]); for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { btSpatialForceVector &hDof = h[m_links[i].m_dofOffset + dof]; // Y_minus_hT_a[dof] = Y[m_links[i].m_dofOffset + dof] - spatAcc[i+1].dot(hDof); } btScalar *invDi = &invD[m_links[i].m_dofOffset*m_links[i].m_dofOffset]; //D^{-1} * (Y - h^{T}*apar) mulMatrix(invDi, Y_minus_hT_a, m_links[i].m_dofCount, m_links[i].m_dofCount, m_links[i].m_dofCount, 1, &joint_accel[m_links[i].m_dofOffset]); spatAcc[i+1] += spatCoriolisAcc[i]; for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) spatAcc[i+1] += m_links[i].m_axes[dof] * joint_accel[m_links[i].m_dofOffset + dof]; if (m_links[i].m_jointFeedback) { m_internalNeedsJointFeedback = true; btVector3 angularBotVec = (spatInertia[i+1]*spatAcc[i+1]+zeroAccSpatFrc[i+1]).m_bottomVec; btVector3 linearTopVec = (spatInertia[i+1]*spatAcc[i+1]+zeroAccSpatFrc[i+1]).m_topVec; if (gJointFeedbackInJointFrame) { //shift the reaction forces to the joint frame //linear (force) component is the same //shift the angular (torque, moment) component using the relative position, m_links[i].m_dVector angularBotVec = angularBotVec - linearTopVec.cross(m_links[i].m_dVector); } if (gJointFeedbackInWorldSpace) { if (isConstraintPass) { m_links[i].m_jointFeedback->m_reactionForces.m_bottomVec += m_links[i].m_cachedWorldTransform.getBasis()*angularBotVec; m_links[i].m_jointFeedback->m_reactionForces.m_topVec += m_links[i].m_cachedWorldTransform.getBasis()*linearTopVec; } else { m_links[i].m_jointFeedback->m_reactionForces.m_bottomVec = m_links[i].m_cachedWorldTransform.getBasis()*angularBotVec; m_links[i].m_jointFeedback->m_reactionForces.m_topVec = m_links[i].m_cachedWorldTransform.getBasis()*linearTopVec; } } else { if (isConstraintPass) { m_links[i].m_jointFeedback->m_reactionForces.m_bottomVec += angularBotVec; m_links[i].m_jointFeedback->m_reactionForces.m_topVec += linearTopVec; } else { m_links[i].m_jointFeedback->m_reactionForces.m_bottomVec = angularBotVec; m_links[i].m_jointFeedback->m_reactionForces.m_topVec = linearTopVec; } } } } // transform base accelerations back to the world frame. btVector3 omegadot_out = rot_from_parent[0].transpose() * spatAcc[0].getAngular(); output[0] = omegadot_out[0]; output[1] = omegadot_out[1]; output[2] = omegadot_out[2]; btVector3 vdot_out = rot_from_parent[0].transpose() * (spatAcc[0].getLinear() + spatVel[0].getAngular().cross(spatVel[0].getLinear())); output[3] = vdot_out[0]; output[4] = vdot_out[1]; output[5] = vdot_out[2]; ///////////////// //printf("q = ["); //printf("%.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f ", m_baseQuat.x(), m_baseQuat.y(), m_baseQuat.z(), m_baseQuat.w(), m_basePos.x(), m_basePos.y(), m_basePos.z()); //for(int link = 0; link < getNumLinks(); ++link) // for(int dof = 0; dof < m_links[link].m_dofCount; ++dof) // printf("%.6f ", m_links[link].m_jointPos[dof]); //printf("]\n"); //// //printf("qd = ["); //for(int dof = 0; dof < getNumDofs() + 6; ++dof) // printf("%.6f ", m_realBuf[dof]); //printf("]\n"); //printf("qdd = ["); //for(int dof = 0; dof < getNumDofs() + 6; ++dof) // printf("%.6f ", output[dof]); //printf("]\n"); ///////////////// // Final step: add the accelerations (times dt) to the velocities. if (!isConstraintPass) { if(dt > 0.) applyDeltaVeeMultiDof(output, dt); } ///// //btScalar angularThres = 1; //btScalar maxAngVel = 0.; //bool scaleDown = 1.; //for(int link = 0; link < m_links.size(); ++link) //{ // if(spatVel[link+1].getAngular().length() > maxAngVel) // { // maxAngVel = spatVel[link+1].getAngular().length(); // scaleDown = angularThres / spatVel[link+1].getAngular().length(); // break; // } //} //if(scaleDown != 1.) //{ // for(int link = 0; link < m_links.size(); ++link) // { // if(m_links[link].m_jointType == btMultibodyLink::eRevolute || m_links[link].m_jointType == btMultibodyLink::eSpherical) // { // for(int dof = 0; dof < m_links[link].m_dofCount; ++dof) // getJointVelMultiDof(link)[dof] *= scaleDown; // } // } //} ///// ///////////////////// if(m_useGlobalVelocities) { for (int i = 0; i < num_links; ++i) { const int parent = m_links[i].m_parent; //rot_from_parent[i+1] = btMatrix3x3(m_links[i].m_cachedRotParentToThis); /// <- done //rot_from_world[i+1] = rot_from_parent[i+1] * rot_from_world[parent+1]; /// <- done fromParent.m_rotMat = rot_from_parent[i+1]; fromParent.m_trnVec = m_links[i].m_cachedRVector; fromWorld.m_rotMat = rot_from_world[i+1]; // vhat_i = i_xhat_p(i) * vhat_p(i) fromParent.transform(spatVel[parent+1], spatVel[i+1]); //nice alternative below (using operator *) but it generates temps ///////////////////////////////////////////////////////////// // now set vhat_i to its true value by doing // vhat_i += qidot * shat_i spatJointVel.setZero(); for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) spatJointVel += m_links[i].m_axes[dof] * getJointVelMultiDof(i)[dof]; // remember vhat_i is really vhat_p(i) (but in current frame) at this point => we need to add velocity across the inboard joint spatVel[i+1] += spatJointVel; fromWorld.transformInverseRotationOnly(spatVel[i+1], m_links[i].m_absFrameTotVelocity); fromWorld.transformInverseRotationOnly(spatJointVel, m_links[i].m_absFrameLocVelocity); } } } void btMultiBody::solveImatrix(const btVector3& rhs_top, const btVector3& rhs_bot, float result[6]) const { int num_links = getNumLinks(); ///solve I * x = rhs, so the result = invI * rhs if (num_links == 0) { // in the case of 0 m_links (i.e. a plain rigid body, not a multibody) rhs * invI is easier result[0] = rhs_bot[0] / m_baseInertia[0]; result[1] = rhs_bot[1] / m_baseInertia[1]; result[2] = rhs_bot[2] / m_baseInertia[2]; result[3] = rhs_top[0] / m_baseMass; result[4] = rhs_top[1] / m_baseMass; result[5] = rhs_top[2] / m_baseMass; } else { if (!m_cachedInertiaValid) { for (int i=0;i<6;i++) { result[i] = 0.f; } return; } /// Special routine for calculating the inverse of a spatial inertia matrix ///the 6x6 matrix is stored as 4 blocks of 3x3 matrices btMatrix3x3 Binv = m_cachedInertiaTopRight.inverse()*-1.f; btMatrix3x3 tmp = m_cachedInertiaLowerRight * Binv; btMatrix3x3 invIupper_right = (tmp * m_cachedInertiaTopLeft + m_cachedInertiaLowerLeft).inverse(); tmp = invIupper_right * m_cachedInertiaLowerRight; btMatrix3x3 invI_upper_left = (tmp * Binv); btMatrix3x3 invI_lower_right = (invI_upper_left).transpose(); tmp = m_cachedInertiaTopLeft * invI_upper_left; tmp[0][0]-= 1.0; tmp[1][1]-= 1.0; tmp[2][2]-= 1.0; btMatrix3x3 invI_lower_left = (Binv * tmp); //multiply result = invI * rhs { btVector3 vtop = invI_upper_left*rhs_top; btVector3 tmp; tmp = invIupper_right * rhs_bot; vtop += tmp; btVector3 vbot = invI_lower_left*rhs_top; tmp = invI_lower_right * rhs_bot; vbot += tmp; result[0] = vtop[0]; result[1] = vtop[1]; result[2] = vtop[2]; result[3] = vbot[0]; result[4] = vbot[1]; result[5] = vbot[2]; } } } void btMultiBody::solveImatrix(const btSpatialForceVector &rhs, btSpatialMotionVector &result) const { int num_links = getNumLinks(); ///solve I * x = rhs, so the result = invI * rhs if (num_links == 0) { // in the case of 0 m_links (i.e. a plain rigid body, not a multibody) rhs * invI is easier result.setAngular(rhs.getAngular() / m_baseInertia); result.setLinear(rhs.getLinear() / m_baseMass); } else { /// Special routine for calculating the inverse of a spatial inertia matrix ///the 6x6 matrix is stored as 4 blocks of 3x3 matrices if (!m_cachedInertiaValid) { result.setLinear(btVector3(0,0,0)); result.setAngular(btVector3(0,0,0)); result.setVector(btVector3(0,0,0),btVector3(0,0,0)); return; } btMatrix3x3 Binv = m_cachedInertiaTopRight.inverse()*-1.f; btMatrix3x3 tmp = m_cachedInertiaLowerRight * Binv; btMatrix3x3 invIupper_right = (tmp * m_cachedInertiaTopLeft + m_cachedInertiaLowerLeft).inverse(); tmp = invIupper_right * m_cachedInertiaLowerRight; btMatrix3x3 invI_upper_left = (tmp * Binv); btMatrix3x3 invI_lower_right = (invI_upper_left).transpose(); tmp = m_cachedInertiaTopLeft * invI_upper_left; tmp[0][0]-= 1.0; tmp[1][1]-= 1.0; tmp[2][2]-= 1.0; btMatrix3x3 invI_lower_left = (Binv * tmp); //multiply result = invI * rhs { btVector3 vtop = invI_upper_left*rhs.getLinear(); btVector3 tmp; tmp = invIupper_right * rhs.getAngular(); vtop += tmp; btVector3 vbot = invI_lower_left*rhs.getLinear(); tmp = invI_lower_right * rhs.getAngular(); vbot += tmp; result.setVector(vtop, vbot); } } } void btMultiBody::mulMatrix(btScalar *pA, btScalar *pB, int rowsA, int colsA, int rowsB, int colsB, btScalar *pC) const { for (int row = 0; row < rowsA; row++) { for (int col = 0; col < colsB; col++) { pC[row * colsB + col] = 0.f; for (int inner = 0; inner < rowsB; inner++) { pC[row * colsB + col] += pA[row * colsA + inner] * pB[col + inner * colsB]; } } } } void btMultiBody::calcAccelerationDeltasMultiDof(const btScalar *force, btScalar *output, btAlignedObjectArray<btScalar> &scratch_r, btAlignedObjectArray<btVector3> &scratch_v) const { // Temporary matrices/vectors -- use scratch space from caller // so that we don't have to keep reallocating every frame int num_links = getNumLinks(); scratch_r.resize(m_dofCount); scratch_v.resize(4*num_links + 4); btScalar * r_ptr = m_dofCount ? &scratch_r[0] : 0; btVector3 * v_ptr = &scratch_v[0]; // zhat_i^A (scratch space) btSpatialForceVector * zeroAccSpatFrc = (btSpatialForceVector *)v_ptr; v_ptr += num_links * 2 + 2; // rot_from_parent (cached from calcAccelerations) const btMatrix3x3 * rot_from_parent = &m_matrixBuf[0]; // hhat (cached), accel (scratch) // hhat is NOT stored for the base (but ahat is) const btSpatialForceVector * h = (btSpatialForceVector *)(m_dofCount > 0 ? &m_vectorBuf[0] : 0); btSpatialMotionVector * spatAcc = (btSpatialMotionVector *)v_ptr; v_ptr += num_links * 2 + 2; // Y_i (scratch), invD_i (cached) const btScalar * invD = m_dofCount > 0 ? &m_realBuf[6 + m_dofCount] : 0; btScalar * Y = r_ptr; //////////////// //aux variables btScalar invD_times_Y[6]; //D^{-1} * Y [dofxdof x dofx1 = dofx1] <=> D^{-1} * u; better moved to buffers since it is recalced in calcAccelerationDeltasMultiDof; num_dof of btScalar would cover all bodies btSpatialMotionVector result; //holds results of the SolveImatrix op; it is a spatial motion vector (accel) btScalar Y_minus_hT_a[6]; //Y - h^{T} * a; it's dofx1 for each body so a single 6x1 temp is enough btSpatialForceVector spatForceVecTemps[6]; //6 temporary spatial force vectors btSpatialTransformationMatrix fromParent; ///////////////// // First 'upward' loop. // Combines CompTreeLinkVelocities and InitTreeLinks from Mirtich. // Fill in zero_acc // -- set to force/torque on the base, zero otherwise if (m_fixedBase) { zeroAccSpatFrc[0].setZero(); } else { //test forces fromParent.m_rotMat = rot_from_parent[0]; fromParent.transformRotationOnly(btSpatialForceVector(-force[0],-force[1],-force[2], -force[3],-force[4],-force[5]), zeroAccSpatFrc[0]); } for (int i = 0; i < num_links; ++i) { zeroAccSpatFrc[i+1].setZero(); } // 'Downward' loop. // (part of TreeForwardDynamics in Mirtich.) for (int i = num_links - 1; i >= 0; --i) { const int parent = m_links[i].m_parent; fromParent.m_rotMat = rot_from_parent[i+1]; fromParent.m_trnVec = m_links[i].m_cachedRVector; for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { Y[m_links[i].m_dofOffset + dof] = force[6 + m_links[i].m_dofOffset + dof] - m_links[i].m_axes[dof].dot(zeroAccSpatFrc[i+1]) ; } btVector3 in_top, in_bottom, out_top, out_bottom; const btScalar *invDi = &invD[m_links[i].m_dofOffset*m_links[i].m_dofOffset]; for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { invD_times_Y[dof] = 0.f; for(int dof2 = 0; dof2 < m_links[i].m_dofCount; ++dof2) { invD_times_Y[dof] += invDi[dof * m_links[i].m_dofCount + dof2] * Y[m_links[i].m_dofOffset + dof2]; } } // Zp += pXi * (Zi + hi*Yi/Di) spatForceVecTemps[0] = zeroAccSpatFrc[i+1]; for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { const btSpatialForceVector &hDof = h[m_links[i].m_dofOffset + dof]; // spatForceVecTemps[0] += hDof * invD_times_Y[dof]; } fromParent.transformInverse(spatForceVecTemps[0], spatForceVecTemps[1]); zeroAccSpatFrc[parent+1] += spatForceVecTemps[1]; } // ptr to the joint accel part of the output btScalar * joint_accel = output + 6; // Second 'upward' loop // (part of TreeForwardDynamics in Mirtich) if (m_fixedBase) { spatAcc[0].setZero(); } else { solveImatrix(zeroAccSpatFrc[0], result); spatAcc[0] = -result; } // now do the loop over the m_links for (int i = 0; i < num_links; ++i) { const int parent = m_links[i].m_parent; fromParent.m_rotMat = rot_from_parent[i+1]; fromParent.m_trnVec = m_links[i].m_cachedRVector; fromParent.transform(spatAcc[parent+1], spatAcc[i+1]); for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) { const btSpatialForceVector &hDof = h[m_links[i].m_dofOffset + dof]; // Y_minus_hT_a[dof] = Y[m_links[i].m_dofOffset + dof] - spatAcc[i+1].dot(hDof); } const btScalar *invDi = &invD[m_links[i].m_dofOffset*m_links[i].m_dofOffset]; mulMatrix(const_cast<btScalar*>(invDi), Y_minus_hT_a, m_links[i].m_dofCount, m_links[i].m_dofCount, m_links[i].m_dofCount, 1, &joint_accel[m_links[i].m_dofOffset]); for(int dof = 0; dof < m_links[i].m_dofCount; ++dof) spatAcc[i+1] += m_links[i].m_axes[dof] * joint_accel[m_links[i].m_dofOffset + dof]; } // transform base accelerations back to the world frame. btVector3 omegadot_out; omegadot_out = rot_from_parent[0].transpose() * spatAcc[0].getAngular(); output[0] = omegadot_out[0]; output[1] = omegadot_out[1]; output[2] = omegadot_out[2]; btVector3 vdot_out; vdot_out = rot_from_parent[0].transpose() * spatAcc[0].getLinear(); output[3] = vdot_out[0]; output[4] = vdot_out[1]; output[5] = vdot_out[2]; ///////////////// //printf("delta = ["); //for(int dof = 0; dof < getNumDofs() + 6; ++dof) // printf("%.2f ", output[dof]); //printf("]\n"); ///////////////// } void btMultiBody::stepPositionsMultiDof(btScalar dt, btScalar *pq, btScalar *pqd) { int num_links = getNumLinks(); // step position by adding dt * velocity //btVector3 v = getBaseVel(); //m_basePos += dt * v; // btScalar *pBasePos = (pq ? &pq[4] : m_basePos); btScalar *pBaseVel = (pqd ? &pqd[3] : &m_realBuf[3]); //note: the !pqd case assumes m_realBuf holds with base velocity at 3,4,5 (should be wrapped for safety) // pBasePos[0] += dt * pBaseVel[0]; pBasePos[1] += dt * pBaseVel[1]; pBasePos[2] += dt * pBaseVel[2]; /////////////////////////////// //local functor for quaternion integration (to avoid error prone redundancy) struct { //"exponential map" based on btTransformUtil::integrateTransform(..) void operator() (const btVector3 &omega, btQuaternion &quat, bool baseBody, btScalar dt) { //baseBody => quat is alias and omega is global coor //!baseBody => quat is alibi and omega is local coor btVector3 axis; btVector3 angvel; if(!baseBody) angvel = quatRotate(quat, omega); //if quat is not m_baseQuat, it is alibi => ok else angvel = omega; btScalar fAngle = angvel.length(); //limit the angular motion if (fAngle * dt > ANGULAR_MOTION_THRESHOLD) { fAngle = btScalar(0.5)*SIMD_HALF_PI / dt; } if ( fAngle < btScalar(0.001) ) { // use Taylor's expansions of sync function axis = angvel*( btScalar(0.5)*dt-(dt*dt*dt)*(btScalar(0.020833333333))*fAngle*fAngle ); } else { // sync(fAngle) = sin(c*fAngle)/t axis = angvel*( btSin(btScalar(0.5)*fAngle*dt)/fAngle ); } if(!baseBody) quat = btQuaternion(axis.x(),axis.y(),axis.z(),btCos( fAngle*dt*btScalar(0.5) )) * quat; else quat = quat * btQuaternion(-axis.x(),-axis.y(),-axis.z(),btCos( fAngle*dt*btScalar(0.5) )); //equivalent to: quat = (btQuaternion(axis.x(),axis.y(),axis.z(),btCos( fAngle*dt*btScalar(0.5) )) * quat.inverse()).inverse(); quat.normalize(); } } pQuatUpdateFun; /////////////////////////////// //pQuatUpdateFun(getBaseOmega(), m_baseQuat, true, dt); // btScalar *pBaseQuat = pq ? pq : m_baseQuat; btScalar *pBaseOmega = pqd ? pqd : &m_realBuf[0]; //note: the !pqd case assumes m_realBuf starts with base omega (should be wrapped for safety) // btQuaternion baseQuat; baseQuat.setValue(pBaseQuat[0], pBaseQuat[1], pBaseQuat[2], pBaseQuat[3]); btVector3 baseOmega; baseOmega.setValue(pBaseOmega[0], pBaseOmega[1], pBaseOmega[2]); pQuatUpdateFun(baseOmega, baseQuat, true, dt); pBaseQuat[0] = baseQuat.x(); pBaseQuat[1] = baseQuat.y(); pBaseQuat[2] = baseQuat.z(); pBaseQuat[3] = baseQuat.w(); //printf("pBaseOmega = %.4f %.4f %.4f\n", pBaseOmega->x(), pBaseOmega->y(), pBaseOmega->z()); //printf("pBaseVel = %.4f %.4f %.4f\n", pBaseVel->x(), pBaseVel->y(), pBaseVel->z()); //printf("baseQuat = %.4f %.4f %.4f %.4f\n", pBaseQuat->x(), pBaseQuat->y(), pBaseQuat->z(), pBaseQuat->w()); if(pq) pq += 7; if(pqd) pqd += 6; // Finally we can update m_jointPos for each of the m_links for (int i = 0; i < num_links; ++i) { btScalar *pJointPos = (pq ? pq : &m_links[i].m_jointPos[0]); btScalar *pJointVel = (pqd ? pqd : getJointVelMultiDof(i)); switch(m_links[i].m_jointType) { case btMultibodyLink::ePrismatic: case btMultibodyLink::eRevolute: { btScalar jointVel = pJointVel[0]; pJointPos[0] += dt * jointVel; break; } case btMultibodyLink::eSpherical: { btVector3 jointVel; jointVel.setValue(pJointVel[0], pJointVel[1], pJointVel[2]); btQuaternion jointOri; jointOri.setValue(pJointPos[0], pJointPos[1], pJointPos[2], pJointPos[3]); pQuatUpdateFun(jointVel, jointOri, false, dt); pJointPos[0] = jointOri.x(); pJointPos[1] = jointOri.y(); pJointPos[2] = jointOri.z(); pJointPos[3] = jointOri.w(); break; } case btMultibodyLink::ePlanar: { pJointPos[0] += dt * getJointVelMultiDof(i)[0]; btVector3 q0_coors_qd1qd2 = getJointVelMultiDof(i)[1] * m_links[i].getAxisBottom(1) + getJointVelMultiDof(i)[2] * m_links[i].getAxisBottom(2); btVector3 no_q0_coors_qd1qd2 = quatRotate(btQuaternion(m_links[i].getAxisTop(0), pJointPos[0]), q0_coors_qd1qd2); pJointPos[1] += m_links[i].getAxisBottom(1).dot(no_q0_coors_qd1qd2) * dt; pJointPos[2] += m_links[i].getAxisBottom(2).dot(no_q0_coors_qd1qd2) * dt; break; } default: { } } m_links[i].updateCacheMultiDof(pq); if(pq) pq += m_links[i].m_posVarCount; if(pqd) pqd += m_links[i].m_dofCount; } } void btMultiBody::fillConstraintJacobianMultiDof(int link, const btVector3 &contact_point, const btVector3 &normal_ang, const btVector3 &normal_lin, btScalar *jac, btAlignedObjectArray<btScalar> &scratch_r, btAlignedObjectArray<btVector3> &scratch_v, btAlignedObjectArray<btMatrix3x3> &scratch_m) const { // temporary space int num_links = getNumLinks(); int m_dofCount = getNumDofs(); scratch_v.resize(3*num_links + 3); //(num_links + base) offsets + (num_links + base) normals_lin + (num_links + base) normals_ang scratch_m.resize(num_links + 1); btVector3 * v_ptr = &scratch_v[0]; btVector3 * p_minus_com_local = v_ptr; v_ptr += num_links + 1; btVector3 * n_local_lin = v_ptr; v_ptr += num_links + 1; btVector3 * n_local_ang = v_ptr; v_ptr += num_links + 1; btAssert(v_ptr - &scratch_v[0] == scratch_v.size()); scratch_r.resize(m_dofCount); btScalar * results = m_dofCount > 0 ? &scratch_r[0] : 0; btMatrix3x3 * rot_from_world = &scratch_m[0]; const btVector3 p_minus_com_world = contact_point - m_basePos; const btVector3 &normal_lin_world = normal_lin; //convenience const btVector3 &normal_ang_world = normal_ang; rot_from_world[0] = btMatrix3x3(m_baseQuat); // omega coeffients first. btVector3 omega_coeffs_world; omega_coeffs_world = p_minus_com_world.cross(normal_lin_world); jac[0] = omega_coeffs_world[0] + normal_ang_world[0]; jac[1] = omega_coeffs_world[1] + normal_ang_world[1]; jac[2] = omega_coeffs_world[2] + normal_ang_world[2]; // then v coefficients jac[3] = normal_lin_world[0]; jac[4] = normal_lin_world[1]; jac[5] = normal_lin_world[2]; //create link-local versions of p_minus_com and normal p_minus_com_local[0] = rot_from_world[0] * p_minus_com_world; n_local_lin[0] = rot_from_world[0] * normal_lin_world; n_local_ang[0] = rot_from_world[0] * normal_ang_world; // Set remaining jac values to zero for now. for (int i = 6; i < 6 + m_dofCount; ++i) { jac[i] = 0; } // Qdot coefficients, if necessary. if (num_links > 0 && link > -1) { // TODO: speed this up -- don't calculate for m_links we don't need. // (Also, we are making 3 separate calls to this function, for the normal & the 2 friction directions, // which is resulting in repeated work being done...) // calculate required normals & positions in the local frames. for (int i = 0; i < num_links; ++i) { // transform to local frame const int parent = m_links[i].m_parent; const btMatrix3x3 mtx(m_links[i].m_cachedRotParentToThis); rot_from_world[i+1] = mtx * rot_from_world[parent+1]; n_local_lin[i+1] = mtx * n_local_lin[parent+1]; n_local_ang[i+1] = mtx * n_local_ang[parent+1]; p_minus_com_local[i+1] = mtx * p_minus_com_local[parent+1] - m_links[i].m_cachedRVector; // calculate the jacobian entry switch(m_links[i].m_jointType) { case btMultibodyLink::eRevolute: { results[m_links[i].m_dofOffset] = n_local_lin[i+1].dot(m_links[i].getAxisTop(0).cross(p_minus_com_local[i+1]) + m_links[i].getAxisBottom(0)); results[m_links[i].m_dofOffset] += n_local_ang[i+1].dot(m_links[i].getAxisTop(0)); break; } case btMultibodyLink::ePrismatic: { results[m_links[i].m_dofOffset] = n_local_lin[i+1].dot(m_links[i].getAxisBottom(0)); break; } case btMultibodyLink::eSpherical: { results[m_links[i].m_dofOffset + 0] = n_local_lin[i+1].dot(m_links[i].getAxisTop(0).cross(p_minus_com_local[i+1]) + m_links[i].getAxisBottom(0)); results[m_links[i].m_dofOffset + 1] = n_local_lin[i+1].dot(m_links[i].getAxisTop(1).cross(p_minus_com_local[i+1]) + m_links[i].getAxisBottom(1)); results[m_links[i].m_dofOffset + 2] = n_local_lin[i+1].dot(m_links[i].getAxisTop(2).cross(p_minus_com_local[i+1]) + m_links[i].getAxisBottom(2)); results[m_links[i].m_dofOffset + 0] += n_local_ang[i+1].dot(m_links[i].getAxisTop(0)); results[m_links[i].m_dofOffset + 1] += n_local_ang[i+1].dot(m_links[i].getAxisTop(1)); results[m_links[i].m_dofOffset + 2] += n_local_ang[i+1].dot(m_links[i].getAxisTop(2)); break; } case btMultibodyLink::ePlanar: { results[m_links[i].m_dofOffset + 0] = n_local_lin[i+1].dot(m_links[i].getAxisTop(0).cross(p_minus_com_local[i+1]));// + m_links[i].getAxisBottom(0)); results[m_links[i].m_dofOffset + 1] = n_local_lin[i+1].dot(m_links[i].getAxisBottom(1)); results[m_links[i].m_dofOffset + 2] = n_local_lin[i+1].dot(m_links[i].getAxisBottom(2)); break; } default: { } } } // Now copy through to output. //printf("jac[%d] = ", link); while (link != -1) { for(int dof = 0; dof < m_links[link].m_dofCount; ++dof) { jac[6 + m_links[link].m_dofOffset + dof] = results[m_links[link].m_dofOffset + dof]; //printf("%.2f\t", jac[6 + m_links[link].m_dofOffset + dof]); } link = m_links[link].m_parent; } //printf("]\n"); } } void btMultiBody::wakeUp() { m_awake = true; } void btMultiBody::goToSleep() { m_awake = false; } void btMultiBody::checkMotionAndSleepIfRequired(btScalar timestep) { extern bool gDisableDeactivation; if (!m_canSleep || gDisableDeactivation) { m_awake = true; m_sleepTimer = 0; return; } // motion is computed as omega^2 + v^2 + (sum of squares of joint velocities) btScalar motion = 0; { for (int i = 0; i < 6 + m_dofCount; ++i) motion += m_realBuf[i] * m_realBuf[i]; } if (motion < SLEEP_EPSILON) { m_sleepTimer += timestep; if (m_sleepTimer > SLEEP_TIMEOUT) { goToSleep(); } } else { m_sleepTimer = 0; if (!m_awake) wakeUp(); } } void btMultiBody::forwardKinematics(btAlignedObjectArray<btQuaternion>& world_to_local,btAlignedObjectArray<btVector3>& local_origin) { int num_links = getNumLinks(); // Cached 3x3 rotation matrices from parent frame to this frame. btMatrix3x3* rot_from_parent =(btMatrix3x3 *) &m_matrixBuf[0]; rot_from_parent[0] = btMatrix3x3(m_baseQuat); //m_baseQuat assumed to be alias!? for (int i = 0; i < num_links; ++i) { rot_from_parent[i+1] = btMatrix3x3(m_links[i].m_cachedRotParentToThis); } int nLinks = getNumLinks(); ///base + num m_links world_to_local.resize(nLinks+1); local_origin.resize(nLinks+1); world_to_local[0] = getWorldToBaseRot(); local_origin[0] = getBasePos(); for (int k=0;k<getNumLinks();k++) { const int parent = getParent(k); world_to_local[k+1] = getParentToLocalRot(k) * world_to_local[parent+1]; local_origin[k+1] = local_origin[parent+1] + (quatRotate(world_to_local[k+1].inverse() , getRVector(k))); } for (int link=0;link<getNumLinks();link++) { int index = link+1; btVector3 posr = local_origin[index]; btScalar quat[4]={-world_to_local[index].x(),-world_to_local[index].y(),-world_to_local[index].z(),world_to_local[index].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); getLink(link).m_cachedWorldTransform = tr; } } void btMultiBody::updateCollisionObjectWorldTransforms(btAlignedObjectArray<btQuaternion>& world_to_local,btAlignedObjectArray<btVector3>& local_origin) { world_to_local.resize(getNumLinks()+1); local_origin.resize(getNumLinks()+1); world_to_local[0] = getWorldToBaseRot(); local_origin[0] = getBasePos(); if (getBaseCollider()) { btVector3 posr = local_origin[0]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4]={-world_to_local[0].x(),-world_to_local[0].y(),-world_to_local[0].z(),world_to_local[0].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); getBaseCollider()->setWorldTransform(tr); } for (int k=0;k<getNumLinks();k++) { const int parent = getParent(k); world_to_local[k+1] = getParentToLocalRot(k) * world_to_local[parent+1]; local_origin[k+1] = local_origin[parent+1] + (quatRotate(world_to_local[k+1].inverse() , getRVector(k))); } for (int m=0;m<getNumLinks();m++) { btMultiBodyLinkCollider* col = getLink(m).m_collider; if (col) { int link = col->m_link; btAssert(link == m); int index = link+1; btVector3 posr = local_origin[index]; // float pos[4]={posr.x(),posr.y(),posr.z(),1}; btScalar quat[4]={-world_to_local[index].x(),-world_to_local[index].y(),-world_to_local[index].z(),world_to_local[index].w()}; btTransform tr; tr.setIdentity(); tr.setOrigin(posr); tr.setRotation(btQuaternion(quat[0],quat[1],quat[2],quat[3])); col->setWorldTransform(tr); } } } int btMultiBody::calculateSerializeBufferSize() const { int sz = sizeof(btMultiBodyData); return sz; } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btMultiBody::serialize(void* dataBuffer, class btSerializer* serializer) const { btMultiBodyData* mbd = (btMultiBodyData*) dataBuffer; getBaseWorldTransform().serialize(mbd->m_baseWorldTransform); mbd->m_baseMass = this->getBaseMass(); getBaseInertia().serialize(mbd->m_baseInertia); { char* name = (char*) serializer->findNameForPointer(m_baseName); mbd->m_baseName = (char*)serializer->getUniquePointer(name); if (mbd->m_baseName) { serializer->serializeName(name); } } mbd->m_numLinks = this->getNumLinks(); if (mbd->m_numLinks) { int sz = sizeof(btMultiBodyLinkData); int numElem = mbd->m_numLinks; btChunk* chunk = serializer->allocate(sz,numElem); btMultiBodyLinkData* memPtr = (btMultiBodyLinkData*)chunk->m_oldPtr; for (int i=0;i<numElem;i++,memPtr++) { memPtr->m_jointType = getLink(i).m_jointType; memPtr->m_dofCount = getLink(i).m_dofCount; memPtr->m_posVarCount = getLink(i).m_posVarCount; getLink(i).m_inertiaLocal.serialize(memPtr->m_linkInertia); memPtr->m_linkMass = getLink(i).m_mass; memPtr->m_parentIndex = getLink(i).m_parent; memPtr->m_jointDamping = getLink(i).m_jointDamping; memPtr->m_jointFriction = getLink(i).m_jointFriction; getLink(i).m_eVector.serialize(memPtr->m_parentComToThisComOffset); getLink(i).m_dVector.serialize(memPtr->m_thisPivotToThisComOffset); getLink(i).m_zeroRotParentToThis.serialize(memPtr->m_zeroRotParentToThis); btAssert(memPtr->m_dofCount<=3); for (int dof = 0;dof<getLink(i).m_dofCount;dof++) { getLink(i).getAxisBottom(dof).serialize(memPtr->m_jointAxisBottom[dof]); getLink(i).getAxisTop(dof).serialize(memPtr->m_jointAxisTop[dof]); memPtr->m_jointTorque[dof] = getLink(i).m_jointTorque[dof]; memPtr->m_jointVel[dof] = getJointVelMultiDof(i)[dof]; } int numPosVar = getLink(i).m_posVarCount; for (int posvar = 0; posvar < numPosVar;posvar++) { memPtr->m_jointPos[posvar] = getLink(i).m_jointPos[posvar]; } { char* name = (char*) serializer->findNameForPointer(m_links[i].m_linkName); memPtr->m_linkName = (char*)serializer->getUniquePointer(name); if (memPtr->m_linkName) { serializer->serializeName(name); } } { char* name = (char*) serializer->findNameForPointer(m_links[i].m_jointName); memPtr->m_jointName = (char*)serializer->getUniquePointer(name); if (memPtr->m_jointName) { serializer->serializeName(name); } } memPtr->m_linkCollider = (btCollisionObjectData*)serializer->getUniquePointer(getLink(i).m_collider); } serializer->finalizeChunk(chunk,btMultiBodyLinkDataName,BT_ARRAY_CODE,(void*) &m_links[0]); } mbd->m_links = mbd->m_numLinks? (btMultiBodyLinkData*) serializer->getUniquePointer((void*)&m_links[0]):0; return btMultiBodyDataName; }
0
0.987626
1
0.987626
game-dev
MEDIA
0.745626
game-dev
0.979296
1
0.979296
followingthefasciaplane/source-engine-diff-check
19,257
misc/game/server/episodic/ai_behavior_alyx_injured.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: FIXME: This will ultimately become a more generic implementation // //============================================================================= #include "cbase.h" #include "ai_memory.h" #include "ai_speech.h" #include "ai_behavior.h" #include "ai_navigator.h" #include "ai_playerally.h" #include "ai_behavior_follow.h" #include "ai_moveprobe.h" #include "ai_behavior_alyx_injured.h" ConVar g_debug_injured_follow( "g_debug_injured_follow", "0" ); ConVar injured_help_plee_range( "injured_help_plee_range", "256" ); #define TLK_INJURED_FOLLOW_TOO_FAR "TLK_INJURED_FOLLOW_TOO_FAR" BEGIN_DATADESC( CAI_BehaviorAlyxInjured ) DEFINE_FIELD( m_flNextWarnTime, FIELD_TIME ), // m_ActivityMap END_DATADESC(); Activity ACT_INJURED_COWER; Activity ACT_GESTURE_INJURED_COWER_FLINCH; #define COVER_DISTANCE 128.0f // Distance behind target to find cover #define MIN_ENEMY_MOB 3 // Number of enemies considerd overwhelming #define MAX_DIST_FROM_FOLLOW_TARGET 256 // If the follow target is farther than this, the NPC will run to it //============================================================================= CAI_BehaviorAlyxInjured::CAI_BehaviorAlyxInjured( void ) : m_flNextWarnTime( 0.0f ) { SetDefLessFunc( m_ActivityMap ); } struct ActivityMap_t { Activity activity; Activity translation; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAI_BehaviorAlyxInjured::PopulateActivityMap( void ) { // Maps one activity to a translated one ActivityMap_t map[] = { // Runs { ACT_RUN, ACT_RUN_HURT }, { ACT_RUN_AIM, ACT_RUN_AIM }, // FIMXE: No appropriate temp anim right now! { ACT_RUN_CROUCH, ACT_RUN_HURT }, { ACT_RUN_CROUCH_AIM, ACT_RUN_HURT }, { ACT_RUN_PROTECTED, ACT_RUN_HURT }, { ACT_RUN_RELAXED, ACT_RUN_HURT }, { ACT_RUN_STIMULATED, ACT_RUN_HURT }, { ACT_RUN_AGITATED, ACT_RUN_HURT }, { ACT_RUN_AIM_RELAXED, ACT_RUN_AIM_RELAXED }, // FIMXE: No appropriate temp anim right now! { ACT_RUN_AIM_STIMULATED, ACT_RUN_AIM_STIMULATED }, // FIMXE: No appropriate temp anim right now! { ACT_RUN_AIM_AGITATED, ACT_RUN_AIM_AGITATED }, // FIMXE: No appropriate temp anim right now! { ACT_RUN_HURT, ACT_RUN_HURT }, // Walks { ACT_WALK, ACT_WALK_HURT }, { ACT_WALK_AIM, ACT_WALK_HURT }, { ACT_WALK_CROUCH, ACT_WALK_HURT }, { ACT_WALK_CROUCH_AIM, ACT_WALK_HURT }, { ACT_WALK_RELAXED, ACT_WALK_HURT }, { ACT_WALK_STIMULATED, ACT_WALK_HURT }, { ACT_WALK_AGITATED, ACT_WALK_HURT }, { ACT_WALK_AIM_RELAXED, ACT_WALK_HURT }, { ACT_WALK_AIM_STIMULATED, ACT_WALK_HURT }, { ACT_WALK_AIM_AGITATED, ACT_WALK_HURT }, { ACT_WALK_HURT, ACT_WALK_HURT }, { ACT_IDLE, ACT_IDLE_HURT }, { ACT_COVER_LOW, ACT_INJURED_COWER }, { ACT_COWER, ACT_INJURED_COWER }, }; // Clear the map m_ActivityMap.RemoveAll(); // Add all translations for ( int i = 0; i < ARRAYSIZE( map ); i++ ) { Assert( m_ActivityMap.Find( map[i].activity ) == m_ActivityMap.InvalidIndex() ); m_ActivityMap.Insert( map[i].activity, map[i].translation ); } } //----------------------------------------------------------------------------- // Purpose: Populate the list after save/load //----------------------------------------------------------------------------- void CAI_BehaviorAlyxInjured::OnRestore( void ) { PopulateActivityMap(); } //----------------------------------------------------------------------------- // Purpose: Populate the list on spawn //----------------------------------------------------------------------------- void CAI_BehaviorAlyxInjured::Spawn( void ) { PopulateActivityMap(); } //----------------------------------------------------------------------------- // Purpose: Get the flinch activity for us to play // Input : bHeavyDamage - // bGesture - // Output : Activity //----------------------------------------------------------------------------- Activity CAI_BehaviorAlyxInjured::GetFlinchActivity( bool bHeavyDamage, bool bGesture ) { // if ( ( bGesture == false ) || ( GetOuter()->GetActivity() != ACT_COWER ) ) return BaseClass::GetFlinchActivity( bHeavyDamage, bGesture ); // Translate the flinch if we're cowering return ACT_GESTURE_INJURED_COWER_FLINCH; } //----------------------------------------------------------------------------- // Purpose: // Input : nActivity - //----------------------------------------------------------------------------- Activity CAI_BehaviorAlyxInjured::NPC_TranslateActivity( Activity nActivity ) { // Find out what the base class wants to do with the activity Activity nNewActivity = BaseClass::NPC_TranslateActivity( nActivity ); // Look it up in the translation map int nIndex = m_ActivityMap.Find( nNewActivity ); if ( m_ActivityMap.IsValidIndex( nIndex ) ) return m_ActivityMap[nIndex]; return nNewActivity; } //----------------------------------------------------------------------------- // Purpose: Determines if Alyx should run away from enemies or stay put // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CAI_BehaviorAlyxInjured::ShouldRunToCover( void ) { Vector vecRetreatPos; float flRetreatRadius = 128.0f; // See how far off from our cover position we are if ( FindCoverFromEnemyBehindTarget( GetFollowTarget(), flRetreatRadius, &vecRetreatPos ) ) { float flDestDistSqr = ( GetOuter()->WorldSpaceCenter() - vecRetreatPos ).LengthSqr(); if ( flDestDistSqr > Square( flRetreatRadius ) ) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: See if we need to follow our goal // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CAI_BehaviorAlyxInjured::ShouldRunToFollowGoal( void ) { // If we're too far from our follow target, we need to chase after them float flDistToFollowGoalSqr = ( GetOuter()->GetAbsOrigin() - GetFollowTarget()->GetAbsOrigin() ).LengthSqr(); if ( flDistToFollowGoalSqr > Square(MAX_DIST_FROM_FOLLOW_TARGET) ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: Translate base schedules into overridden forms //----------------------------------------------------------------------------- int CAI_BehaviorAlyxInjured::TranslateSchedule( int scheduleType ) { switch( scheduleType ) { case SCHED_RUN_FROM_ENEMY: case SCHED_RUN_FROM_ENEMY_MOB: { // Get under cover if we're able to if ( ShouldRunToCover() ) return SCHED_INJURED_RUN_FROM_ENEMY; // Run to our follow goal if we're too far away from it if ( ShouldRunToFollowGoal() ) return SCHED_FOLLOW; // Cower if surrounded if ( HasCondition( COND_INJURED_OVERWHELMED ) ) return SCHED_INJURED_COWER; // Face our enemies return SCHED_INJURED_FEAR_FACE; } break; case SCHED_RUN_FROM_ENEMY_FALLBACK: return SCHED_INJURED_COWER; break; } return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- // Purpose: Pick up failure cases and handle them //----------------------------------------------------------------------------- int CAI_BehaviorAlyxInjured::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ) { // Failed schedules switch( failedSchedule ) { case SCHED_RUN_FROM_ENEMY: case SCHED_RUN_FROM_ENEMY_MOB: case SCHED_FOLLOW: return SCHED_INJURED_COWER; } // Failed tasks switch( failedTask ) { case TASK_FIND_COVER_FROM_ENEMY: case TASK_FIND_INJURED_COVER_FROM_ENEMY: // Only cower if we're already near enough to our follow target float flDistToFollowTargetSqr = ( GetOuter()->GetAbsOrigin() - GetFollowTarget()->GetAbsOrigin() ).LengthSqr(); if ( flDistToFollowTargetSqr > Square( 256 ) ) return SCHED_FOLLOW; return SCHED_INJURED_COWER; break; } return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode ); } //----------------------------------------------------------------------------- // Purpose: Find the general direction enemies are coming towards us at //----------------------------------------------------------------------------- bool CAI_BehaviorAlyxInjured::FindThreatDirection2D( const Vector &vecSource, Vector *vecOut ) { // Find the general direction our threat is coming from bool bValid = false; Vector vecScratch; AIEnemiesIter_t iter; // Iterate through all known enemies for( AI_EnemyInfo_t *pMemory = GetOuter()->GetEnemies()->GetFirst(&iter); pMemory != NULL; pMemory = GetOuter()->GetEnemies()->GetNext(&iter) ) { if ( pMemory == NULL || pMemory->hEnemy == NULL ) continue; vecScratch = ( vecSource - pMemory->hEnemy->WorldSpaceCenter() ); VectorNormalize( vecScratch ); (*vecOut) += vecScratch; bValid = true; } // Find the general direction (*vecOut).z = 0.0f; VectorNormalize( (*vecOut) ); return bValid; } //----------------------------------------------------------------------------- // Purpose: Find a position that hides us from our threats while interposing the // target entity between us and the threat // Input : pTarget - entity to hide behind // flRadius - Radius around the target to search // *vecOut - position //----------------------------------------------------------------------------- bool CAI_BehaviorAlyxInjured::FindCoverFromEnemyBehindTarget( CBaseEntity *pTarget, float flRadius, Vector *vecOut ) { if ( pTarget == NULL ) return false; Vector vecTargetPos = pTarget->GetAbsOrigin(); Vector vecThreatDir = vec3_origin; // Find our threat direction and base our cover on that if ( FindThreatDirection2D( vecTargetPos, &vecThreatDir ) ) { // Get a general location for taking cover Vector vecTestPos = vecTargetPos + ( vecThreatDir * flRadius ); if ( g_debug_injured_follow.GetBool() ) { NDebugOverlay::HorzArrow( GetOuter()->GetAbsOrigin(), vecTestPos, 8.0f, 255, 255, 0, 32, true, 2.0f ); } // Make sure we never move towards our threat to get to cover! Vector vecMoveDir = GetOuter()->GetAbsOrigin() - vecTestPos; VectorNormalize( vecMoveDir ); float flDotToCover = DotProduct( vecMoveDir, vecThreatDir ); if ( flDotToCover > 0.0f ) { if ( g_debug_injured_follow.GetBool() ) { NDebugOverlay::HorzArrow( GetOuter()->GetAbsOrigin(), vecTestPos, 8.0f, 255, 0, 0, 32, true, 2.0f ); } return false; } AIMoveTrace_t moveTrace; GetOuter()->GetMoveProbe()->MoveLimit( NAV_GROUND, GetOuter()->GetAbsOrigin(), vecTestPos, MASK_SOLID_BRUSHONLY, NULL, 0, &moveTrace ); bool bWithinRangeToGoal = ( moveTrace.vEndPosition - vecTestPos ).Length2DSqr() < Square( GetOuter()->GetHullWidth() * 3.0f ); bool bCanStandAtGoal = GetOuter()->GetMoveProbe()->CheckStandPosition( moveTrace.vEndPosition, MASK_SOLID_BRUSHONLY ); if ( bWithinRangeToGoal == false || bCanStandAtGoal == false ) { if ( g_debug_injured_follow.GetBool() ) { NDebugOverlay::SweptBox( GetOuter()->GetAbsOrigin(), vecTestPos, GetOuter()->GetHullMins(), GetOuter()->GetHullMaxs(), vec3_angle, 255, 0, 0, 0, 2.0f ); } return false; } // Accept it *vecOut = moveTrace.vEndPosition; if ( g_debug_injured_follow.GetBool() ) { NDebugOverlay::SweptBox( GetOuter()->GetAbsOrigin(), (*vecOut), GetOuter()->GetHullMins(), GetOuter()->GetHullMaxs(), vec3_angle, 0, 255, 0, 0, 2.0f ); } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: // Input : *pTask - //----------------------------------------------------------------------------- void CAI_BehaviorAlyxInjured::StartTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_FIND_COVER_FROM_ENEMY: { CBaseEntity *pLeader = GetFollowTarget(); if ( !pLeader ) { BaseClass::StartTask( pTask ); break; } // Find a position behind our follow target Vector coverPos = vec3_invalid; if ( FindCoverFromEnemyBehindTarget( pLeader, COVER_DISTANCE, &coverPos ) ) { AI_NavGoal_t goal( GOALTYPE_LOCATION, coverPos, ACT_RUN, AIN_HULL_TOLERANCE, AIN_DEF_FLAGS ); GetOuter()->GetNavigator()->SetGoal( goal ); GetOuter()->m_flMoveWaitFinished = gpGlobals->curtime + pTask->flTaskData; TaskComplete(); return; } // Couldn't find anything TaskFail( FAIL_NO_COVER ); break; } default: BaseClass::StartTask( pTask ); break; } } //----------------------------------------------------------------------------- // Purpose: Whether or not Alyx is injured //----------------------------------------------------------------------------- bool CAI_BehaviorAlyxInjured::IsInjured( void ) const { return IsAlyxInInjuredMode(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CAI_BehaviorAlyxInjured::GatherConditions( void ) { BaseClass::GatherConditions(); // Always stomp over this ClearCondition( COND_INJURED_TOO_FAR_FROM_PLAYER ); ClearCondition( COND_INJURED_OVERWHELMED ); // See if we're overwhelmed by foes if ( NumKnownEnemiesInRadius( GetOuter()->GetAbsOrigin(), COVER_DISTANCE ) >= MIN_ENEMY_MOB ) { SetCondition( COND_INJURED_OVERWHELMED ); } // Determines whether we consider ourselves in danger bool bInDanger = ( HasCondition( COND_LIGHT_DAMAGE ) || HasCondition( COND_HEAVY_DAMAGE ) || HasCondition( COND_INJURED_OVERWHELMED ) ); // See if we're too far away from the player and in danger if ( AI_IsSinglePlayer() && bInDanger ) { bool bWarnPlayer = false; // This only works in single-player CBasePlayer *pPlayer = UTIL_PlayerByIndex( 1 ); if ( pPlayer != NULL ) { // FIXME: This distance may need to be the length of the shortest walked path between the follower and the target // Get our approximate distance to the player float flDistToPlayer = UTIL_DistApprox2D( GetOuter()->GetAbsOrigin(), pPlayer->GetAbsOrigin() ); if ( flDistToPlayer > injured_help_plee_range.GetFloat() ) { bWarnPlayer = true; } else if ( flDistToPlayer > (injured_help_plee_range.GetFloat()*0.5f) && HasCondition( COND_SEE_PLAYER ) == false ) { // Cut our distance in half if we can't see the player bWarnPlayer = true; } } // Yell for help! if ( bWarnPlayer ) { // FIXME: This should be routed through the normal speaking code with a system to emit from the player's suit. CBasePlayer *pPlayer = UTIL_PlayerByIndex( 1 ); //float flPlayerDistSqr = ( GetOuter()->GetAbsOrigin() - pPlayer->GetAbsOrigin() ).LengthSqr(); // If the player is too far away or we can't see him //if ( HasCondition( COND_SEE_PLAYER ) == false || flPlayerDistSqr > Square( 128 ) ) { if ( m_flNextWarnTime < gpGlobals->curtime ) { pPlayer->EmitSound( "npc_alyx.injured_too_far" ); m_flNextWarnTime = gpGlobals->curtime + random->RandomFloat( 3.0f, 5.0f ); } } /* else { SpeakIfAllowed( TLK_INJURED_FOLLOW_TOO_FAR ); m_flNextWarnTime = gpGlobals->curtime + random->RandomFloat( 3.0f, 5.0f ); } */ SetCondition( COND_INJURED_TOO_FAR_FROM_PLAYER ); } } } //----------------------------------------------------------------------------- // Purpose: Speak a concept if we're able to //----------------------------------------------------------------------------- void CAI_BehaviorAlyxInjured::SpeakIfAllowed( AIConcept_t concept ) { CAI_Expresser *pExpresser = GetOuter()->GetExpresser(); if ( pExpresser == NULL ) return; // Must be able to speak the concept if ( pExpresser->CanSpeakConcept( concept ) ) { pExpresser->Speak( concept ); } } //----------------------------------------------------------------------------- // Purpose: Get the number of known enemies within a radius to a point //----------------------------------------------------------------------------- int CAI_BehaviorAlyxInjured::NumKnownEnemiesInRadius( const Vector &vecSource, float flRadius ) { int nNumEnemies = 0; float flRadiusSqr = Square( flRadius ); AIEnemiesIter_t iter; // Iterate through all known enemies for( AI_EnemyInfo_t *pMemory = GetEnemies()->GetFirst(&iter); pMemory != NULL; pMemory = GetEnemies()->GetNext(&iter) ) { if ( pMemory == NULL || pMemory->hEnemy == NULL ) continue; // Must hate or fear them if ( GetOuter()->IRelationType( pMemory->hEnemy ) != D_HT && GetOuter()->IRelationType( pMemory->hEnemy ) != D_FR ) continue; // Count only the enemies I've seen recently if ( gpGlobals->curtime - pMemory->timeLastSeen > 0.5f ) continue; // Must be within the radius we've specified float flEnemyDistSqr = ( vecSource - pMemory->hEnemy->GetAbsOrigin() ).Length2DSqr(); if ( flEnemyDistSqr < flRadiusSqr ) { nNumEnemies++; } } return nNumEnemies; } // ---------------------------------------------- // Custom AI declarations // ---------------------------------------------- AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( CAI_BehaviorAlyxInjured ) { DECLARE_ACTIVITY( ACT_GESTURE_INJURED_COWER_FLINCH ) DECLARE_ACTIVITY( ACT_INJURED_COWER ) DECLARE_CONDITION( COND_INJURED_TOO_FAR_FROM_PLAYER ) DECLARE_CONDITION( COND_INJURED_OVERWHELMED ) DECLARE_TASK( TASK_FIND_INJURED_COVER_FROM_ENEMY ) DEFINE_SCHEDULE ( SCHED_INJURED_COWER, " Tasks" // TOOD: Announce cower " TASK_PLAY_SEQUENCE ACTIVITY:ACT_COWER" " TASK_WAIT 2" "" " Interrupts" " COND_GIVE_WAY" " COND_PLAYER_PUSHING" ) DEFINE_SCHEDULE ( SCHED_INJURED_FEAR_FACE, " Tasks" " TASK_STOP_MOVING 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // FIXME: Scared idle? " TASK_FACE_ENEMY 0" "" " Interrupts" " COND_GIVE_WAY" " COND_PLAYER_PUSHING" ); DEFINE_SCHEDULE ( SCHED_INJURED_RUN_FROM_ENEMY, " Tasks" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_INJURED_COWER" " TASK_STOP_MOVING 0" " TASK_FIND_COVER_FROM_ENEMY 0" " TASK_RUN_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" "" " Interrupts" ); AI_END_CUSTOM_SCHEDULE_PROVIDER() } //----------------------------------------------------------------------------- // CAI_InjuredFollowGoal //----------------------------------------------------------------------------- BEGIN_DATADESC( CAI_InjuredFollowGoal ) END_DATADESC() LINK_ENTITY_TO_CLASS( ai_goal_injured_follow, CAI_InjuredFollowGoal ); //------------------------------------- void CAI_InjuredFollowGoal::EnableGoal( CAI_BaseNPC *pAI ) { CAI_BehaviorAlyxInjured *pBehavior; if ( !pAI->GetBehavior( &pBehavior ) ) return; if ( GetGoalEntity() == NULL ) return; pBehavior->SetFollowGoal( this ); } //------------------------------------- void CAI_InjuredFollowGoal::DisableGoal( CAI_BaseNPC *pAI ) { CAI_BehaviorAlyxInjured *pBehavior; if ( !pAI->GetBehavior( &pBehavior ) ) return; pBehavior->ClearFollowGoal( this ); }
0
0.990608
1
0.990608
game-dev
MEDIA
0.98212
game-dev
0.959366
1
0.959366
OreCruncher/DynamicSurroundingsFabric
2,405
common/src/main/java/org/orecruncher/dsurround/eventing/handlers/BlockUpdateHandler.java
package org.orecruncher.dsurround.eventing.handlers; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.world.level.block.state.BlockState; import org.orecruncher.dsurround.eventing.ClientEventHooks; import org.orecruncher.dsurround.eventing.ClientState; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; public class BlockUpdateHandler { private static final Set<BlockPos> updatedPositions = new HashSet<>(16); private static final Set<BlockPos> expandedPositions = new HashSet<>(48); private static final Vec3i[] offsets = new Vec3i[27]; static { int x = 0; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) for (int k = -1; k < 2; k++) offsets[x++] = new Vec3i(i, j, k); ClientState.TICK_END.register(BlockUpdateHandler::tick); } /** * Called from a mixin to record that a block position was updated. * * @param pos Block position that has been updated */ public static void blockPositionUpdate(BlockPos pos, BlockState oldState, BlockState newState) { updatedPositions.add(pos); } /** * Called at the tail end of a tick once all updates have been received and * processed by the client. * * @param ignored MinecraftClient instance - ignored */ private static void tick(Minecraft ignored) { var updates = expand(); updates.ifPresent(positions -> ClientEventHooks.BLOCK_UPDATE.raise().onBlockUpdates(positions)); } private static Optional<Collection<BlockPos>> expand() { if (updatedPositions.isEmpty()) return Optional.empty(); // Need to expand out the updates to adjacent blocks. A state change // of a block may affect how the adjacent blocks are handled. Can't rely on // neighbor state changes since the effects the mod produces are virtual // and do not exist server side. expandedPositions.clear(); for (final BlockPos center : updatedPositions) for (final Vec3i offset : offsets) expandedPositions.add(center.offset(offset)); // Have to clear for the next run updatedPositions.clear(); return Optional.of(expandedPositions); } }
0
0.74968
1
0.74968
game-dev
MEDIA
0.907489
game-dev
0.878298
1
0.878298
dalenewman/Transformalize
3,460
src/Transformalize/Transforms/ReplaceTransform.cs
#region license // Transformalize // Configurable Extract, Transform, and Load // Copyright 2013-2025 Dale Newman // // 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. #endregion using System; using System.Collections.Generic; using Transformalize.Configuration; using Transformalize.Contracts; namespace Transformalize.Transforms { public class ReplaceTransform : StringTransform { private readonly Field _input; private readonly Func<IRow, string> _getOldValue; private readonly Func<IRow, string> _getNewValue; public ReplaceTransform(IContext context = null) : base(context, "string") { if (IsMissingContext()) { return; } if (IsMissing(Context.Operation.OldValue)) { return; } _input = SingleInput(); Context.Operation.OldValue = Context.Operation.OldValue.Replace("\\r", "\r"); Context.Operation.OldValue = Context.Operation.OldValue.Replace("\\n", "\n"); var oldIsField = Context.Entity.FieldMatcher.IsMatch(Context.Operation.OldValue); if (oldIsField && Context.Entity.TryGetField(Context.Operation.OldValue, out var oldField)) { _getOldValue = row => GetString(row, oldField); Context.Debug(() => $"replace transform's old value comes from the field: {oldField.Alias}"); } else { _getOldValue = row => Context.Operation.OldValue; Context.Debug(() => $"replace transform's old value is literal: {Context.Operation.OldValue}"); } var newIsField = Context.Entity.FieldMatcher.IsMatch(Context.Operation.NewValue); if (newIsField && Context.Entity.TryGetField(Context.Operation.NewValue, out var newField)) { _getNewValue = row => GetString(row, newField); Context.Debug(() => $"replace transform's new value comes from the field: {newField.Alias}"); } else { _getNewValue = row => Context.Operation.NewValue; Context.Debug(() => $"replace transform's new value is literal: {Context.Operation.NewValue}"); } } public override IRow Operate(IRow row) { var oldValue = _getOldValue(row); if (oldValue != string.Empty) { row[Context.Field] = GetString(row, _input).Replace(oldValue, _getNewValue(row)); } return row; } public override IEnumerable<OperationSignature> GetSignatures() { yield return new OperationSignature("replace") { Parameters = new List<OperationParameter> { new OperationParameter("old-value"), new OperationParameter("new-value","") } }; } public override string ToString() { return Context?.Operation != null ? $"replace(old-value:{Context.Operation.OldValue},new-value:{Context.Operation.NewValue})" : "replace(old-value,new-value)"; } } }
0
0.908887
1
0.908887
game-dev
MEDIA
0.299855
game-dev
0.899789
1
0.899789
luna-rs/luna
2,417
src/main/java/io/luna/game/action/impl/QueuedAction.java
package io.luna.game.action.impl; import com.google.common.primitives.Ints; import io.luna.game.action.Action; import io.luna.game.action.ActionType; import io.luna.game.action.TimeSource; import io.luna.game.model.mob.Mob; import io.luna.game.task.Task; /** * An {@link Action} implementation similar to {@link ThrottledAction}, except it queues up to {@code 1} additional * equivalent action instead of throttling the action. This behaviour is required for content such as * alchemy and thieving. * <p> * <p> * These actions are executed instantly. The {@link #delay} parameter simply refers to how long the player must wait * to execute a subsequent action. * * @author lare96 */ public abstract class QueuedAction<T extends Mob> extends Action<T> { /** * The duration of this action. */ private final int delay; /** * The time source. */ private final TimeSource source; /** * Creates a new {@link QueuedAction}. * * @param mob The mob assigned to this action. * @param source The time source. * @param delay The delay of this action. How long (in ticks) the mob must wait before executions of this action. */ public QueuedAction(T mob, TimeSource source, int delay) { super(mob, ActionType.WEAK); this.delay = delay; this.source = source; } private void runAndWait() { source.reset(); execute(); source.setWaiting(true); } @Override public boolean run() { if (source.ready(delay)) { // Run normally, time source is ready. runAndWait(); } else if (source.isWaiting()) { // We've received a throttled action, queue it. source.setWaiting(false); int remaining = Ints.saturatedCast(delay - source.getDurationTicks()); if (remaining < 1) { // No remaining ticks, run right away. runAndWait(); } else { // Schedule for later. world.schedule(new Task(false, remaining) { @Override protected void execute() { runAndWait(); cancel(); } }); } } return true; } /** * Executes this action. */ public abstract void execute(); }
0
0.879752
1
0.879752
game-dev
MEDIA
0.62473
game-dev
0.950667
1
0.950667
Brackeys/MultiplayerFPS-Tutorial
1,081
MultiplayerFPS/Assets/Standard Assets/Utility/LerpControlledBob.cs
using System; using System.Collections; using UnityEngine; namespace UnityStandardAssets.Utility { [Serializable] public class LerpControlledBob { public float BobDuration; public float BobAmount; private float m_Offset = 0f; // provides the offset that can be used public float Offset() { return m_Offset; } public IEnumerator DoBobCycle() { // make the camera move down slightly float t = 0f; while (t < BobDuration) { m_Offset = Mathf.Lerp(0f, BobAmount, t/BobDuration); t += Time.deltaTime; yield return new WaitForFixedUpdate(); } // make it move back to neutral t = 0f; while (t < BobDuration) { m_Offset = Mathf.Lerp(BobAmount, 0f, t/BobDuration); t += Time.deltaTime; yield return new WaitForFixedUpdate(); } m_Offset = 0f; } } }
0
0.644065
1
0.644065
game-dev
MEDIA
0.897366
game-dev
0.902271
1
0.902271
liquidbounceplusreborn/LiquidbouncePlus-Reborn
4,310
src/main/java/net/ccbluex/liquidbounce/utils/EntityUtils.java
/* * LiquidBounce+ Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge. * https://github.com/WYSI-Foundation/LiquidBouncePlus/ */ package net.ccbluex.liquidbounce.utils; import net.ccbluex.liquidbounce.LiquidBounce; import net.ccbluex.liquidbounce.features.module.modules.combat.NoFriends; import net.ccbluex.liquidbounce.features.module.modules.misc.AntiBot; import net.ccbluex.liquidbounce.features.module.modules.world.Teams; import net.ccbluex.liquidbounce.utils.render.ColorUtils; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.entity.monster.EntityGhast; import net.minecraft.entity.monster.EntityGolem; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntityBat; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.scoreboard.ScorePlayerTeam; public final class EntityUtils extends MinecraftInstance { public static boolean targetInvisible = false; public static boolean targetPlayer = true; public static boolean targetMobs = true; public static boolean targetAnimals = false; public static boolean targetDead = false; public static boolean isSelected(final Entity entity, final boolean canAttackCheck) { if(entity instanceof EntityLivingBase && (targetDead || entity.isEntityAlive()) && entity != mc.thePlayer) { if(targetInvisible || !entity.isInvisible()) { if(targetPlayer && entity instanceof EntityPlayer) { final EntityPlayer entityPlayer = (EntityPlayer) entity; if(canAttackCheck) { if(AntiBot.Companion.isBot(entityPlayer)) return false; if (isFriend(entityPlayer) && !LiquidBounce.moduleManager.getModule(NoFriends.class).getState()) return false; if(entityPlayer.isSpectator()) return false; final Teams teams = LiquidBounce.moduleManager.getModule(Teams.class); return !teams.getState() || !teams.isInYourTeam(entityPlayer); } return true; } return targetMobs && isMob(entity) || targetAnimals && isAnimal(entity); } } return false; } public static boolean isFriend(final Entity entity) { return entity instanceof EntityPlayer && entity.getName() != null && LiquidBounce.fileManager.friendsConfig.isFriend(ColorUtils.stripColor(entity.getName())); } public static boolean isAnimal(final Entity entity) { return entity instanceof EntityAnimal || entity instanceof EntitySquid || entity instanceof EntityGolem || entity instanceof EntityBat; } public static boolean isMob(final Entity entity) { return entity instanceof EntityMob || entity instanceof EntityVillager || entity instanceof EntitySlime || entity instanceof EntityGhast || entity instanceof EntityDragon; } public static String getName(final NetworkPlayerInfo networkPlayerInfoIn) { return networkPlayerInfoIn.getDisplayName() != null ? networkPlayerInfoIn.getDisplayName().getFormattedText() : ScorePlayerTeam.formatPlayerName(networkPlayerInfoIn.getPlayerTeam(), networkPlayerInfoIn.getGameProfile().getName()); } public static int getPing(final EntityPlayer entityPlayer) { if(entityPlayer == null) return 0; final NetworkPlayerInfo networkPlayerInfo = mc.getNetHandler().getPlayerInfo(entityPlayer.getUniqueID()); return networkPlayerInfo == null ? 0 : networkPlayerInfo.getResponseTime(); } public static boolean isRendered(Entity entityToCheck){ return mc.theWorld != null && mc.theWorld.getLoadedEntityList().contains(entityToCheck); } }
0
0.889766
1
0.889766
game-dev
MEDIA
0.952538
game-dev
0.948466
1
0.948466
FirstPersonKSP/AvionicsSystems
1,071
GameData/MOARdV/MAS_ASET/RetroButton/MAS_RB_SAS_Normal.cfg
PROP { name = MAS_RB_SAS_Normal MODEL { model = ASET/ASET_Props/Control/RetroButton/RetroButton } MODULE { name = MASComponent COLLIDER_EVENT { name = Collider collider = ButtonTopObj sound = ASET/ASET_Props/Sounds/buttonbeep volume = 1 onClick = fc.SetSASMode(3) variable = fc.GetSAS() } TRANSLATION { name = Button press translation transform = ButtonGrp startTranslation = 0, 0, 0 endTranslation = 0, -0.0025, 0 blend = true speed = 8.0 variable = fc.GetSASMode() == 3 } ANIMATION { name = Button lighting animation = RetroButtonLightAnim variable = 0.333 * (fc.Select(fc.GetSAS() and (fc.GetSASMode() == 3), 2, 0) + fc.GetPersistentAsNumber("Backlight")) } TEXT_LABEL { name = Label transform = ButtonNameTextObj fontSize = 2.50 lineSpacing = 1.0 font = Liberation Sans style = Bold alignment = Center anchor = MiddleCenter transformOffset = 0.0077, -0.0045 emissive = never passiveColor = COLOR_MOARdV_BlackPrintedText text = NORMAL } } }
0
0.89452
1
0.89452
game-dev
MEDIA
0.660514
game-dev
0.853262
1
0.853262
JavaSaBr/jmonkeybuilder
3,864
src/main/java/com/ss/editor/ui/component/painting/spawn/SpawnPaintingStateWithEditorTool.java
package com.ss.editor.ui.component.painting.spawn; import com.jme3.math.Vector3f; import com.ss.editor.annotation.FxThread; import com.ss.editor.control.painting.spawn.SpawnToolControl.SpawnMethod; import com.ss.editor.ui.component.painting.impl.AbstractPaintingStateWithEditorTool; import org.jetbrains.annotations.NotNull; import java.util.Arrays; /** * The state of spawn painting component. * * @author JavaSaBr */ public class SpawnPaintingStateWithEditorTool extends AbstractPaintingStateWithEditorTool { /** * The constant serialVersionUID. */ public static final long serialVersionUID = 4; /** * The selected models. */ @NotNull private String[] selectedModels; /** * The models min scale. */ @NotNull private Vector3f minScale; /** * The models max scale. */ @NotNull private Vector3f maxScale; /** * The models padding. */ @NotNull private Vector3f padding; /** * The spawn method. */ private int method; public SpawnPaintingStateWithEditorTool() { this.method = SpawnMethod.BATCH.ordinal(); this.selectedModels = new String[SpawnPaintingComponent.AVAILABLE_MODELS]; this.minScale = Vector3f.UNIT_XYZ.clone(); this.maxScale = Vector3f.UNIT_XYZ.clone(); this.padding = Vector3f.ZERO.clone(); } /** * Set the spawn method. * * @param method the spawn method. */ @FxThread public void setMethod(int method) { final boolean changed = getMethod() != method; this.method = method; if (changed) notifyChange(); } /** * Get the spawn method. * * @return the spawn method. */ @FxThread public int getMethod() { return method; } /** * Set the models min scale. * * @param minScale the models min scale. */ @FxThread public void setMinScale(@NotNull Vector3f minScale) { final boolean changed = !minScale.equals(getMinScale()); this.minScale = minScale; if (changed) notifyChange(); } /** * Set the models max scale. * * @param maxScale the models max scale. */ @FxThread public void setMaxScale(@NotNull Vector3f maxScale) { final boolean changed = !maxScale.equals(getMaxScale()); this.maxScale = maxScale; if (changed) notifyChange(); } /** * Set the models padding. * * @param padding the models padding. */ @FxThread public void setPadding(@NotNull Vector3f padding) { final boolean changed = !padding.equals(getPadding()); this.padding = padding; if (changed) notifyChange(); } /** * Get the models min scale. * * @return the models min scale. */ @FxThread public @NotNull Vector3f getMinScale() { return minScale; } /** * Get the models max scale. * * @return the models max scale. */ @FxThread public @NotNull Vector3f getMaxScale() { return maxScale; } /** * Get the models padding. * * @return the models padding. */ @FxThread public @NotNull Vector3f getPadding() { return padding; } /** * Set the selected models. * * @param selectedModels the selected models. */ @FxThread public void setSelectedModels(@NotNull String[] selectedModels) { final boolean changed = !Arrays.equals(getSelectedModels(), selectedModels); this.selectedModels = selectedModels; if (changed) notifyChange(); } /** * Get the selected models. * * @return the selected models. */ @FxThread public @NotNull String[] getSelectedModels() { return selectedModels; } }
0
0.754826
1
0.754826
game-dev
MEDIA
0.66435
game-dev,graphics-rendering
0.839101
1
0.839101
cocos/cocos-engine
6,109
cocos/physics/bullet/instantiated.ts
/* Copyright (c) 2020-2023 Xiamen Yaji Software Co., Ltd. https://www.cocos.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm'; import { BUILD, LOAD_BULLET_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants'; import { game } from '../../game'; import { error, log, sys } from '../../core'; import { NativeCodeBundleMode } from '../../misc/webassembly-support'; import type { BulletCache } from './bullet-cache'; //corresponds to bulletType in bullet-compile export enum EBulletType{ EBulletTypeVec3 = 0, EBulletTypeQuat, EBulletTypeTransform, EBulletTypeMotionState, EBulletTypeCollisionObject, EBulletTypeCollisionShape, EBulletTypeCharacterController, EBulletTypeStridingMeshInterface, EBulletTypeTriangleMesh, EBulletTypeCollisionDispatcher, EBulletTypeDbvtBroadPhase, EBulletTypeSequentialImpulseConstraintSolver, EBulletTypeCollisionWorld, EBulletTypeTypedConstraint, EBulletTypeDebugDraw } //corresponds to btTriangleRaycastCallback::EFlags export enum EBulletTriangleRaycastFlag { NONE = 0, FilterBackfaces = 1 << 0, KeepUnflippedNormal = 1 << 1, //Prevents returned face normal getting flipped when a ray hits a back-facing triangle UseSubSimplexConvexCastRaytest = 1 << 2, //default, uses an approximate but faster ray versus convex intersection algorithm UseGjkConvexCastRaytest = 1 << 3 } //btIDebugDraw::EBulletDebugDrawModes export enum EBulletDebugDrawModes { DBG_NoDebug=0, DBG_DrawWireframe = 1, DBG_DrawAabb=2, DBG_DrawFeaturesText=4, DBG_DrawContactPoints=8, DBG_NoDeactivation=16, DBG_NoHelpText = 32, DBG_DrawText=64, DBG_ProfileTimings = 128, DBG_EnableSatComparison = 256, DBG_DisableBulletLCP = 512, DBG_EnableCCD = 1024, DBG_DrawConstraints = (1 << 11), DBG_DrawConstraintLimits = (1 << 12), DBG_FastWireframe = (1 << 13), DBG_DrawNormals = (1 << 14), DBG_DrawFrames = (1 << 15), DBG_MAX_DEBUG_DRAW_MODE } interface BtCache { CACHE: typeof BulletCache, BODY_CACHE_NAME: string, CCT_CACHE_NAME: string, } // eslint-disable-next-line import/no-mutable-exports export let bt = {} as Bullet.instance; export const btCache = {} as BtCache; btCache.BODY_CACHE_NAME = 'body'; btCache.CCT_CACHE_NAME = 'cct'; function initWASM (wasmFactory, wasmUrl: string): Promise<void> { return new Promise<void>((resolve, reject) => { const errorMessage = (err: any): string => `[bullet]: bullet wasm lib load failed: ${err}`; wasmFactory({ instantiateWasm ( importObject: WebAssembly.Imports, receiveInstance: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void, ) { // NOTE: the Promise return by instantiateWasm hook can't be caught. instantiateWasm(wasmUrl, importObject).then((result) => { receiveInstance(result.instance, result.module); }).catch((err) => reject(errorMessage(err))); }, }).then((instance: any) => { log('[bullet]:bullet wasm lib loaded.'); bt = instance as Bullet.instance; globalThis.Bullet = bt as any; }).then(resolve).catch((err: any) => reject(errorMessage(err))); }); } function initASM (asmFactory): Promise<void> { if (asmFactory != null) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return asmFactory().then((instance: any) => { log('[bullet]:bullet asm lib loaded.'); bt = instance as Bullet.instance; }); } else { return new Promise<void>((resolve, reject) => { resolve(); }); } } function shouldUseWasmModule (): boolean { if (NATIVE_CODE_BUNDLE_MODE === (NativeCodeBundleMode.BOTH as number)) { return sys.hasFeature(sys.Feature.WASM); } else if (NATIVE_CODE_BUNDLE_MODE === (NativeCodeBundleMode.WASM as number)) { return true; } else { return false; } } export function waitForAmmoInstantiation (): Promise<void> { const errorReport = (msg: any): void => { error(msg); }; return ensureWasmModuleReady().then(() => { if (shouldUseWasmModule()) { return Promise.all([ import('external:emscripten/bullet/bullet.release.wasm.js'), import('external:emscripten/bullet/bullet.release.wasm.wasm'), ]).then(([ { default: bulletWasmFactory }, { default: bulletWasmUrl }, ]) => initWASM(bulletWasmFactory, bulletWasmUrl)); } else { return import('external:emscripten/bullet/bullet.release.asm.js').then( ({ default: bulletAsmFactory }) => initASM(bulletAsmFactory), ); } }).catch(errorReport); } if (!BUILD || !LOAD_BULLET_MANUALLY) { game.onPostInfrastructureInitDelegate.add(waitForAmmoInstantiation); }
0
0.697318
1
0.697318
game-dev
MEDIA
0.724141
game-dev
0.948114
1
0.948114
FabricMC/fabric
3,989
fabric-api-lookup-api-v1/src/main/java/net/fabricmc/fabric/impl/lookup/block/BlockApiCacheImpl.java
/* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.fabricmc.fabric.impl.lookup.block; import org.jetbrains.annotations.Nullable; import net.minecraft.block.BlockState; import net.minecraft.block.entity.BlockEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerBlockEntityEvents; import net.fabricmc.fabric.api.lookup.v1.block.BlockApiCache; import net.fabricmc.fabric.api.lookup.v1.block.BlockApiLookup; public final class BlockApiCacheImpl<A, C> implements BlockApiCache<A, C> { private final BlockApiLookupImpl<A, C> lookup; private final ServerWorld world; private final BlockPos pos; /** * We always cache the block entity, even if it's null. We rely on BE load and unload events to invalidate the cache when necessary. * blockEntityCacheValid maintains whether the cache is valid or not. */ private boolean blockEntityCacheValid = false; private BlockEntity cachedBlockEntity = null; /** * We also cache the BlockApiProvider at the target position. We check if the block state has changed to invalidate the cache. * lastState maintains for which block state the cachedProvider is valid. */ private BlockState lastState = null; private BlockApiLookup.BlockApiProvider<A, C> cachedProvider = null; public BlockApiCacheImpl(BlockApiLookupImpl<A, C> lookup, ServerWorld world, BlockPos pos) { ((ServerWorldCache) world).fabric_registerCache(pos, this); this.lookup = lookup; this.world = world; this.pos = pos.toImmutable(); } public void invalidate() { blockEntityCacheValid = false; cachedBlockEntity = null; lastState = null; cachedProvider = null; } @Nullable @Override public A find(@Nullable BlockState state, C context) { // Update block entity cache getBlockEntity(); // Get block state if (state == null) { if (cachedBlockEntity != null) { state = cachedBlockEntity.getCachedState(); } else { state = world.getBlockState(pos); } } // Get provider if (lastState != state) { cachedProvider = lookup.getProvider(state.getBlock()); lastState = state; } // Query the provider A instance = null; if (cachedProvider != null) { instance = cachedProvider.find(world, pos, state, cachedBlockEntity, context); } if (instance != null) { return instance; } // Query the fallback providers for (BlockApiLookup.BlockApiProvider<A, C> fallbackProvider : lookup.getFallbackProviders()) { instance = fallbackProvider.find(world, pos, state, cachedBlockEntity, context); if (instance != null) { return instance; } } return null; } @Override @Nullable public BlockEntity getBlockEntity() { if (!blockEntityCacheValid) { cachedBlockEntity = world.getBlockEntity(pos); blockEntityCacheValid = true; } return cachedBlockEntity; } @Override public BlockApiLookupImpl<A, C> getLookup() { return lookup; } @Override public ServerWorld getWorld() { return world; } @Override public BlockPos getPos() { return pos; } static { ServerBlockEntityEvents.BLOCK_ENTITY_LOAD.register((blockEntity, world) -> { ((ServerWorldCache) world).fabric_invalidateCache(blockEntity.getPos()); }); ServerBlockEntityEvents.BLOCK_ENTITY_UNLOAD.register((blockEntity, world) -> { ((ServerWorldCache) world).fabric_invalidateCache(blockEntity.getPos()); }); } }
0
0.850253
1
0.850253
game-dev
MEDIA
0.880369
game-dev
0.91453
1
0.91453
LuaLS/lua-language-server
3,580
script/glob/matcher.lua
local m = require 'lpeglabel' local Slash = m.S('/\\')^1 local Symbol = m.S',{}[]*?/\\' local Char = 1 - Symbol local Path = (1 - m.S[[\/*?"<>|]])^1 * Slash local NoWord = #(m.P(-1) + Symbol) local function whatHappened() return m.Cmt(m.P(1)^1, function (...) print(...) end) end local mt = {} mt.__index = mt mt.__name = 'matcher' function mt:exp(state, index) local exp = state[index] if not exp then return end if exp.type == 'word' then return self:word(exp, state, index + 1) elseif exp.type == 'char' then return self:char(exp, state, index + 1) elseif exp.type == '**' then return self:anyPath(exp, state, index + 1) elseif exp.type == '*' then return self:anyChar(exp, state, index + 1) elseif exp.type == '?' then return self:oneChar(exp, state, index + 1) elseif exp.type == '[]' then return self:range(exp, state, index + 1) elseif exp.type == '/' then return self:slash(exp, state, index + 1) end end function mt:word(exp, state, index) local current = self:exp(exp.value, 1) local after = self:exp(state, index) if after then return current * Slash * after else return current end end function mt:char(exp, state, index) local current = m.P(exp.value) local after = self:exp(state, index) if after then return current * after * NoWord else return current * NoWord end end function mt:anyPath(_, state, index) local after = self:exp(state, index) if after then return m.P { 'Main', Main = after + Path * m.V'Main' } else return Path^0 end end function mt:anyChar(_, state, index) local after = self:exp(state, index) if after then return m.P { 'Main', Main = after + Char * m.V'Main' } else return Char^0 end end function mt:oneChar(_, state, index) local after = self:exp(state, index) if after then return Char * after else return Char end end function mt:range(exp, state, index) local after = self:exp(state, index) local ranges = {} local selects = {} for _, range in ipairs(exp.value) do if #range == 1 then selects[#selects+1] = range[1] elseif #range == 2 then ranges[#ranges+1] = range[1] .. range[2] end end local current = m.S(table.concat(selects)) + m.R(table.unpack(ranges)) if after then return current * after else return current end end function mt:slash(_, state, index) local after = self:exp(state, index) if after then return after else self.needDirectory = true return nil end end function mt:pattern(state) if state.root then local after = self:exp(state, 1) if after then return m.C(after) else return nil end else return m.C(self:anyPath(nil, state, 1)) end end function mt:isNeedDirectory() return self.needDirectory == true end function mt:isNegative() return self.state.neg == true end function mt:__call(path) return self.matcher:match(path) end return function (state, options) local self = setmetatable({ options = options, state = state, }, mt) self.matcher = self:pattern(state) if not self.matcher then return nil end return self end
0
0.928843
1
0.928843
game-dev
MEDIA
0.372917
game-dev
0.982565
1
0.982565
Kirkezz/rttt
28,333
SDL/src/joystick/gdk/SDL_gameinputjoystick.c
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_internal.h" #ifdef SDL_JOYSTICK_GAMEINPUT #include "../SDL_sysjoystick.h" #include "../usb_ids.h" #define COBJMACROS #include <gameinput.h> // Default value for SDL_HINT_JOYSTICK_GAMEINPUT #if defined(SDL_PLATFORM_GDK) #define SDL_GAMEINPUT_DEFAULT true #else #define SDL_GAMEINPUT_DEFAULT false #endif enum { SDL_GAMEPAD_BUTTON_GAMEINPUT_SHARE = 11 }; typedef struct GAMEINPUT_InternalDevice { IGameInputDevice *device; char path[(APP_LOCAL_DEVICE_ID_SIZE * 2) + 1]; char *name; SDL_GUID guid; // generated by SDL SDL_JoystickID device_instance; // generated by SDL const GameInputDeviceInfo *info; bool isAdded; bool isDeleteRequested; } GAMEINPUT_InternalDevice; typedef struct GAMEINPUT_InternalList { GAMEINPUT_InternalDevice **devices; int count; } GAMEINPUT_InternalList; typedef struct joystick_hwdata { GAMEINPUT_InternalDevice *devref; bool report_sensors; GameInputRumbleParams rumbleParams; GameInputCallbackToken system_button_callback_token; } GAMEINPUT_InternalJoystickHwdata; static GAMEINPUT_InternalList g_GameInputList = { NULL }; static SDL_SharedObject *g_hGameInputDLL = NULL; static IGameInput *g_pGameInput = NULL; static GameInputCallbackToken g_GameInputCallbackToken = GAMEINPUT_INVALID_CALLBACK_TOKEN_VALUE; static Uint64 g_GameInputTimestampOffset; static bool GAMEINPUT_InternalIsGamepad(const GameInputDeviceInfo *info) { if (info->supportedInput & GameInputKindGamepad) { return true; } return false; } static bool GAMEINPUT_InternalAddOrFind(IGameInputDevice *pDevice) { GAMEINPUT_InternalDevice **devicelist = NULL; GAMEINPUT_InternalDevice *elem = NULL; const GameInputDeviceInfo *info = NULL; Uint16 bus = SDL_HARDWARE_BUS_USB; Uint16 vendor = 0; Uint16 product = 0; Uint16 version = 0; const char *manufacturer_string = NULL; const char *product_string = NULL; char tmp[4]; int idx = 0; SDL_AssertJoysticksLocked(); info = IGameInputDevice_GetDeviceInfo(pDevice); if (info->capabilities & GameInputDeviceCapabilityWireless) { bus = SDL_HARDWARE_BUS_BLUETOOTH; } else { bus = SDL_HARDWARE_BUS_USB; } vendor = info->vendorId; product = info->productId; version = (info->firmwareVersion.major << 8) | info->firmwareVersion.minor; if (SDL_JoystickHandledByAnotherDriver(&SDL_GAMEINPUT_JoystickDriver, vendor, product, version, "")) { return true; } for (idx = 0; idx < g_GameInputList.count; ++idx) { elem = g_GameInputList.devices[idx]; if (elem && elem->device == pDevice) { // we're already added elem->isDeleteRequested = false; return true; } } elem = (GAMEINPUT_InternalDevice *)SDL_calloc(1, sizeof(*elem)); if (!elem) { return false; } devicelist = (GAMEINPUT_InternalDevice **)SDL_realloc(g_GameInputList.devices, sizeof(elem) * (g_GameInputList.count + 1LL)); if (!devicelist) { SDL_free(elem); return false; } // Generate a device path for (idx = 0; idx < APP_LOCAL_DEVICE_ID_SIZE; ++idx) { SDL_snprintf(tmp, SDL_arraysize(tmp), "%02hhX", info->deviceId.value[idx]); SDL_strlcat(elem->path, tmp, SDL_arraysize(tmp)); } if (info->deviceStrings) { // In theory we could get the manufacturer and product strings here, but they're NULL for all the controllers I've tested } if (info->displayName) { // This could give us a product string, but it's NULL for all the controllers I've tested } IGameInputDevice_AddRef(pDevice); elem->device = pDevice; elem->name = SDL_CreateJoystickName(vendor, product, manufacturer_string, product_string); elem->guid = SDL_CreateJoystickGUID(bus, vendor, product, version, manufacturer_string, product_string, 'g', 0); elem->device_instance = SDL_GetNextObjectID(); elem->info = info; g_GameInputList.devices = devicelist; g_GameInputList.devices[g_GameInputList.count++] = elem; return true; } static bool GAMEINPUT_InternalRemoveByIndex(int idx) { GAMEINPUT_InternalDevice **devicelist = NULL; GAMEINPUT_InternalDevice *elem; int bytes = 0; SDL_AssertJoysticksLocked(); if (idx < 0 || idx >= g_GameInputList.count) { return SDL_SetError("GAMEINPUT_InternalRemoveByIndex argument idx %d is out of range", idx); } elem = g_GameInputList.devices[idx]; if (elem) { IGameInputDevice_Release(elem->device); SDL_free(elem->name); SDL_free(elem); } g_GameInputList.devices[idx] = NULL; if (g_GameInputList.count == 1) { // last element in the list, free the entire list then SDL_free(g_GameInputList.devices); g_GameInputList.devices = NULL; } else { if (idx != g_GameInputList.count - 1) { bytes = sizeof(*devicelist) * (g_GameInputList.count - idx); SDL_memmove(&g_GameInputList.devices[idx], &g_GameInputList.devices[idx + 1], bytes); } } // decrement the count and return --g_GameInputList.count; return true; } static GAMEINPUT_InternalDevice *GAMEINPUT_InternalFindByIndex(int idx) { // We're guaranteed that the index is in range when this is called SDL_AssertJoysticksLocked(); return g_GameInputList.devices[idx]; } static void CALLBACK GAMEINPUT_InternalJoystickDeviceCallback( _In_ GameInputCallbackToken callbackToken, _In_ void* context, _In_ IGameInputDevice* device, _In_ uint64_t timestamp, _In_ GameInputDeviceStatus currentStatus, _In_ GameInputDeviceStatus previousStatus) { int idx = 0; GAMEINPUT_InternalDevice *elem = NULL; if (!device) { // This should never happen, but ignore it if it does return; } SDL_LockJoysticks(); if (currentStatus & GameInputDeviceConnected) { GAMEINPUT_InternalAddOrFind(device); } else { for (idx = 0; idx < g_GameInputList.count; ++idx) { elem = g_GameInputList.devices[idx]; if (elem && elem->device == device) { // will be deleted on the next Detect call elem->isDeleteRequested = true; break; } } } SDL_UnlockJoysticks(); } static void GAMEINPUT_JoystickDetect(void); static bool GAMEINPUT_JoystickInit(void) { HRESULT hR; if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_GAMEINPUT, SDL_GAMEINPUT_DEFAULT)) { return true; } if (!g_hGameInputDLL) { g_hGameInputDLL = SDL_LoadObject("gameinput.dll"); if (!g_hGameInputDLL) { return false; } } if (!g_pGameInput) { typedef HRESULT (WINAPI *GameInputCreate_t)(IGameInput * *gameInput); GameInputCreate_t GameInputCreateFunc = (GameInputCreate_t)SDL_LoadFunction(g_hGameInputDLL, "GameInputCreate"); if (!GameInputCreateFunc) { return false; } hR = GameInputCreateFunc(&g_pGameInput); if (FAILED(hR)) { return SDL_SetError("GameInputCreate failure with HRESULT of %08lX", hR); } } hR = IGameInput_RegisterDeviceCallback(g_pGameInput, NULL, GameInputKindController, GameInputDeviceConnected, GameInputBlockingEnumeration, NULL, GAMEINPUT_InternalJoystickDeviceCallback, &g_GameInputCallbackToken); if (FAILED(hR)) { return SDL_SetError("IGameInput::RegisterDeviceCallback failure with HRESULT of %08lX", hR); } // Calculate the relative offset between SDL timestamps and GameInput timestamps Uint64 now = SDL_GetTicksNS(); uint64_t timestampUS = IGameInput_GetCurrentTimestamp(g_pGameInput); g_GameInputTimestampOffset = (SDL_NS_TO_US(now) - timestampUS); GAMEINPUT_JoystickDetect(); return true; } static int GAMEINPUT_JoystickGetCount(void) { SDL_AssertJoysticksLocked(); return g_GameInputList.count; } static void GAMEINPUT_JoystickDetect(void) { int idx; GAMEINPUT_InternalDevice *elem = NULL; SDL_AssertJoysticksLocked(); for (idx = 0; idx < g_GameInputList.count; ++idx) { elem = g_GameInputList.devices[idx]; if (!elem) { continue; } if (!elem->isAdded) { SDL_PrivateJoystickAdded(elem->device_instance); elem->isAdded = true; } if (elem->isDeleteRequested || !(IGameInputDevice_GetDeviceStatus(elem->device) & GameInputDeviceConnected)) { SDL_PrivateJoystickRemoved(elem->device_instance); GAMEINPUT_InternalRemoveByIndex(idx--); } } } static bool GAMEINPUT_JoystickIsDevicePresent(Uint16 vendor_id, Uint16 product_id, Uint16 version, const char *name) { SDL_AssertJoysticksLocked(); if (g_pGameInput) { if (vendor_id == USB_VENDOR_MICROSOFT && product_id == USB_PRODUCT_XBOX_ONE_XBOXGIP_CONTROLLER) { // The Xbox One controller shows up as a hardcoded raw input VID/PID, which we definitely handle return true; } for (int i = 0; i < g_GameInputList.count; ++i) { GAMEINPUT_InternalDevice *elem = g_GameInputList.devices[i]; if (elem && vendor_id == elem->info->vendorId && product_id == elem->info->productId) { return true; } } } return false; } static const char *GAMEINPUT_JoystickGetDeviceName(int device_index) { return GAMEINPUT_InternalFindByIndex(device_index)->name; } static const char *GAMEINPUT_JoystickGetDevicePath(int device_index) { // APP_LOCAL_DEVICE_ID as a hex string, since it's required for some association callbacks return GAMEINPUT_InternalFindByIndex(device_index)->path; } static int GAMEINPUT_JoystickGetDeviceSteamVirtualGamepadSlot(int device_index) { return -1; } static int GAMEINPUT_JoystickGetDevicePlayerIndex(int device_index) { return -1; } static void GAMEINPUT_JoystickSetDevicePlayerIndex(int device_index, int player_index) { } static SDL_GUID GAMEINPUT_JoystickGetDeviceGUID(int device_index) { return GAMEINPUT_InternalFindByIndex(device_index)->guid; } static SDL_JoystickID GAMEINPUT_JoystickGetDeviceInstanceID(int device_index) { return GAMEINPUT_InternalFindByIndex(device_index)->device_instance; } static void GAMEINPUT_UpdatePowerInfo(SDL_Joystick *joystick, IGameInputDevice *device) { GameInputBatteryState battery_state; SDL_PowerState state; int percent = 0; SDL_zero(battery_state); IGameInputDevice_GetBatteryState(device, &battery_state); switch (battery_state.status) { case GameInputBatteryNotPresent: state = SDL_POWERSTATE_NO_BATTERY; break; case GameInputBatteryDischarging: state = SDL_POWERSTATE_ON_BATTERY; break; case GameInputBatteryIdle: state = SDL_POWERSTATE_CHARGED; break; case GameInputBatteryCharging: state = SDL_POWERSTATE_CHARGING; break; default: state = SDL_POWERSTATE_UNKNOWN; break; } if (battery_state.fullChargeCapacity > 0.0f) { percent = (int)SDL_roundf((battery_state.remainingCapacity / battery_state.fullChargeCapacity) * 100.0f); } SDL_SendJoystickPowerInfo(joystick, state, percent); } #ifdef IGameInput_RegisterSystemButtonCallback static void CALLBACK GAMEINPUT_InternalSystemButtonCallback( _In_ GameInputCallbackToken callbackToken, _In_ void * context, _In_ IGameInputDevice * device, _In_ uint64_t timestampUS, _In_ GameInputSystemButtons currentButtons, _In_ GameInputSystemButtons previousButtons) { SDL_Joystick *joystick = (SDL_Joystick *)context; GameInputSystemButtons changedButtons = (previousButtons ^ currentButtons); if (changedButtons) { Uint64 timestamp = SDL_US_TO_NS(timestampUS + g_GameInputTimestampOffset); SDL_LockJoysticks(); if (changedButtons & GameInputSystemButtonGuide) { bool down = ((currentButtons & GameInputSystemButtonGuide) != 0); SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, down); } if (changedButtons & GameInputSystemButtonShare) { bool down = ((currentButtons & GameInputSystemButtonShare) != 0); SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GAMEINPUT_SHARE, down); } SDL_UnlockJoysticks(); } } #endif // IGameInput_RegisterSystemButtonCallback static bool GAMEINPUT_JoystickOpen(SDL_Joystick *joystick, int device_index) { GAMEINPUT_InternalDevice *elem = GAMEINPUT_InternalFindByIndex(device_index); const GameInputDeviceInfo *info = elem->info; GAMEINPUT_InternalJoystickHwdata *hwdata = NULL; if (!elem) { return false; } hwdata = (GAMEINPUT_InternalJoystickHwdata *)SDL_calloc(1, sizeof(*hwdata)); if (!hwdata) { return false; } hwdata->devref = elem; joystick->hwdata = hwdata; if (GAMEINPUT_InternalIsGamepad(info)) { joystick->naxes = 6; joystick->nbuttons = 11; joystick->nhats = 1; #ifdef IGameInput_RegisterSystemButtonCallback if (info->supportedSystemButtons != GameInputSystemButtonNone) { if (info->supportedSystemButtons & GameInputSystemButtonShare) { ++joystick->nbuttons; } #if 1 // The C macro in GameInput.h version 10.0.26100 refers to a focus policy which I guess has been removed from the final API? #undef IGameInput_RegisterSystemButtonCallback #define IGameInput_RegisterSystemButtonCallback(This, device, buttonFilter, context, callbackFunc, callbackToken) ((This)->lpVtbl->RegisterSystemButtonCallback(This, device, buttonFilter, context, callbackFunc, callbackToken)) #endif IGameInput_RegisterSystemButtonCallback(g_pGameInput, elem->device, (GameInputSystemButtonGuide | GameInputSystemButtonShare), joystick, GAMEINPUT_InternalSystemButtonCallback, &hwdata->system_button_callback_token); } #endif // IGameInput_RegisterSystemButtonCallback } else { joystick->naxes = info->controllerAxisCount; joystick->nbuttons = info->controllerButtonCount; joystick->nhats = info->controllerSwitchCount; } if (info->supportedRumbleMotors & (GameInputRumbleLowFrequency | GameInputRumbleHighFrequency)) { SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true); } if (info->supportedRumbleMotors & (GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger)) { SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN, true); } if (info->supportedInput & GameInputKindTouch) { SDL_PrivateJoystickAddTouchpad(joystick, info->touchPointCount); } if (info->supportedInput & GameInputKindMotion) { // FIXME: What's the sensor update rate? SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_GYRO, 250.0f); SDL_PrivateJoystickAddSensor(joystick, SDL_SENSOR_ACCEL, 250.0f); } if (info->capabilities & GameInputDeviceCapabilityWireless) { joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRELESS; } else { joystick->connection_state = SDL_JOYSTICK_CONNECTION_WIRED; } return true; } static bool GAMEINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble) { // don't check for caps here, since SetRumbleState doesn't return any result - we don't need to check it GAMEINPUT_InternalJoystickHwdata *hwdata = joystick->hwdata; GameInputRumbleParams *params = &hwdata->rumbleParams; params->lowFrequency = (float)low_frequency_rumble / (float)SDL_MAX_UINT16; params->highFrequency = (float)high_frequency_rumble / (float)SDL_MAX_UINT16; IGameInputDevice_SetRumbleState(hwdata->devref->device, params); return true; } static bool GAMEINPUT_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble) { // don't check for caps here, since SetRumbleState doesn't return any result - we don't need to check it GAMEINPUT_InternalJoystickHwdata *hwdata = joystick->hwdata; GameInputRumbleParams *params = &hwdata->rumbleParams; params->leftTrigger = (float)left_rumble / (float)SDL_MAX_UINT16; params->rightTrigger = (float)right_rumble / (float)SDL_MAX_UINT16; IGameInputDevice_SetRumbleState(hwdata->devref->device, params); return true; } static bool GAMEINPUT_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue) { return SDL_Unsupported(); } static bool GAMEINPUT_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size) { return SDL_Unsupported(); } static bool GAMEINPUT_JoystickSetSensorsEnabled(SDL_Joystick *joystick, bool enabled) { joystick->hwdata->report_sensors = enabled; return true; } static void GAMEINPUT_JoystickUpdate(SDL_Joystick *joystick) { GAMEINPUT_InternalJoystickHwdata *hwdata = joystick->hwdata; IGameInputDevice *device = hwdata->devref->device; const GameInputDeviceInfo *info = hwdata->devref->info; IGameInputReading *reading = NULL; Uint64 timestamp; GameInputGamepadState state; HRESULT hR; hR = IGameInput_GetCurrentReading(g_pGameInput, info->supportedInput, device, &reading); if (FAILED(hR)) { // don't SetError here since there can be a legitimate case when there's no reading avail return; } timestamp = SDL_US_TO_NS(IGameInputReading_GetTimestamp(reading) + g_GameInputTimestampOffset); if (GAMEINPUT_InternalIsGamepad(info)) { static WORD s_XInputButtons[] = { GameInputGamepadA, // SDL_GAMEPAD_BUTTON_SOUTH GameInputGamepadB, // SDL_GAMEPAD_BUTTON_EAST GameInputGamepadX, // SDL_GAMEPAD_BUTTON_WEST GameInputGamepadY, // SDL_GAMEPAD_BUTTON_NORTH GameInputGamepadView, // SDL_GAMEPAD_BUTTON_BACK 0, // The guide button is not available GameInputGamepadMenu, // SDL_GAMEPAD_BUTTON_START GameInputGamepadLeftThumbstick, // SDL_GAMEPAD_BUTTON_LEFT_STICK GameInputGamepadRightThumbstick, // SDL_GAMEPAD_BUTTON_RIGHT_STICK GameInputGamepadLeftShoulder, // SDL_GAMEPAD_BUTTON_LEFT_SHOULDER GameInputGamepadRightShoulder, // SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER }; Uint8 btnidx = 0, hat = 0; if (IGameInputReading_GetGamepadState(reading, &state)) { for (btnidx = 0; btnidx < SDL_arraysize(s_XInputButtons); ++btnidx) { WORD button_mask = s_XInputButtons[btnidx]; if (!button_mask) { continue; } bool down = ((state.buttons & button_mask) != 0); SDL_SendJoystickButton(timestamp, joystick, btnidx, down); } if (state.buttons & GameInputGamepadDPadUp) { hat |= SDL_HAT_UP; } if (state.buttons & GameInputGamepadDPadDown) { hat |= SDL_HAT_DOWN; } if (state.buttons & GameInputGamepadDPadLeft) { hat |= SDL_HAT_LEFT; } if (state.buttons & GameInputGamepadDPadRight) { hat |= SDL_HAT_RIGHT; } SDL_SendJoystickHat(timestamp, joystick, 0, hat); #define CONVERT_AXIS(v) (Sint16)(((v) < 0.0f) ? ((v)*32768.0f) : ((v)*32767.0f)) SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, CONVERT_AXIS(state.leftThumbstickX)); SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, CONVERT_AXIS(-state.leftThumbstickY)); SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, CONVERT_AXIS(state.rightThumbstickX)); SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, CONVERT_AXIS(-state.rightThumbstickY)); #undef CONVERT_AXIS #define CONVERT_TRIGGER(v) (Sint16)((v)*65535.0f - 32768.0f) SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, CONVERT_TRIGGER(state.leftTrigger)); SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, CONVERT_TRIGGER(state.rightTrigger)); #undef CONVERT_TRIGGER } } else { bool *button_state = SDL_stack_alloc(bool, info->controllerButtonCount); float *axis_state = SDL_stack_alloc(float, info->controllerAxisCount); if (button_state) { uint32_t i; uint32_t button_count = IGameInputReading_GetControllerButtonState(reading, info->controllerButtonCount, button_state); for (i = 0; i < button_count; ++i) { SDL_SendJoystickButton(timestamp, joystick, (Uint8)i, button_state[i]); } SDL_stack_free(button_state); } #define CONVERT_AXIS(v) (Sint16)((v)*65535.0f - 32768.0f) if (axis_state) { uint32_t i; uint32_t axis_count = IGameInputReading_GetControllerAxisState(reading, info->controllerAxisCount, axis_state); for (i = 0; i < axis_count; ++i) { SDL_SendJoystickAxis(timestamp, joystick, (Uint8)i, CONVERT_AXIS(axis_state[i])); } SDL_stack_free(axis_state); } #undef CONVERT_AXIS } if (info->supportedInput & GameInputKindTouch) { GameInputTouchState *touch_state = SDL_stack_alloc(GameInputTouchState, info->touchPointCount); if (touch_state) { uint32_t i; uint32_t touch_count = IGameInputReading_GetTouchState(reading, info->touchPointCount, touch_state); for (i = 0; i < touch_count; ++i) { GameInputTouchState *touch = &touch_state[i]; // FIXME: We should use touch->touchId to track fingers instead of using i below SDL_SendJoystickTouchpad(timestamp, joystick, 0, i, true, touch->positionX * info->touchSensorInfo[i].resolutionX, touch->positionY * info->touchSensorInfo[0].resolutionY, touch->pressure); } SDL_stack_free(touch_state); } } if (hwdata->report_sensors) { GameInputMotionState motion_state; if (IGameInputReading_GetMotionState(reading, &motion_state)) { // FIXME: How do we interpret the motion data? } } IGameInputReading_Release(reading); // FIXME: We can poll this at a much lower rate GAMEINPUT_UpdatePowerInfo(joystick, device); } static void GAMEINPUT_JoystickClose(SDL_Joystick* joystick) { GAMEINPUT_InternalJoystickHwdata *hwdata = joystick->hwdata; if (hwdata->system_button_callback_token) { IGameInput_UnregisterCallback(g_pGameInput, hwdata->system_button_callback_token, 5000); } SDL_free(hwdata); joystick->hwdata = NULL; } static void GAMEINPUT_JoystickQuit(void) { if (g_pGameInput) { // free the callback IGameInput_UnregisterCallback(g_pGameInput, g_GameInputCallbackToken, /*timeoutInUs:*/ 10000); g_GameInputCallbackToken = GAMEINPUT_INVALID_CALLBACK_TOKEN_VALUE; // free the list while (g_GameInputList.count > 0) { GAMEINPUT_InternalRemoveByIndex(0); } IGameInput_Release(g_pGameInput); g_pGameInput = NULL; } if (g_hGameInputDLL) { SDL_UnloadObject(g_hGameInputDLL); g_hGameInputDLL = NULL; } } static bool GAMEINPUT_JoystickGetGamepadMapping(int device_index, SDL_GamepadMapping *out) { GAMEINPUT_InternalDevice *elem = GAMEINPUT_InternalFindByIndex(device_index); if (!GAMEINPUT_InternalIsGamepad(elem->info)) { return false; } out->a.kind = EMappingKind_Button; out->a.target = SDL_GAMEPAD_BUTTON_SOUTH; out->b.kind = EMappingKind_Button; out->b.target = SDL_GAMEPAD_BUTTON_EAST; out->x.kind = EMappingKind_Button; out->x.target = SDL_GAMEPAD_BUTTON_WEST; out->y.kind = EMappingKind_Button; out->y.target = SDL_GAMEPAD_BUTTON_NORTH; out->back.kind = EMappingKind_Button; out->back.target = SDL_GAMEPAD_BUTTON_BACK; #ifdef IGameInput_RegisterSystemButtonCallback if (elem->info->supportedSystemButtons & GameInputSystemButtonGuide) { out->guide.kind = EMappingKind_Button; out->guide.target = SDL_GAMEPAD_BUTTON_GUIDE; } if (elem->info->supportedSystemButtons & GameInputSystemButtonShare) { out->misc1.kind = EMappingKind_Button; out->misc1.target = SDL_GAMEPAD_BUTTON_GAMEINPUT_SHARE; } #endif out->start.kind = EMappingKind_Button; out->start.target = SDL_GAMEPAD_BUTTON_START; out->leftstick.kind = EMappingKind_Button; out->leftstick.target = SDL_GAMEPAD_BUTTON_LEFT_STICK; out->rightstick.kind = EMappingKind_Button; out->rightstick.target = SDL_GAMEPAD_BUTTON_RIGHT_STICK; out->leftshoulder.kind = EMappingKind_Button; out->leftshoulder.target = SDL_GAMEPAD_BUTTON_LEFT_SHOULDER; out->rightshoulder.kind = EMappingKind_Button; out->rightshoulder.target = SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER; out->dpup.kind = EMappingKind_Hat; out->dpup.target = SDL_HAT_UP; out->dpdown.kind = EMappingKind_Hat; out->dpdown.target = SDL_HAT_DOWN; out->dpleft.kind = EMappingKind_Hat; out->dpleft.target = SDL_HAT_LEFT; out->dpright.kind = EMappingKind_Hat; out->dpright.target = SDL_HAT_RIGHT; out->leftx.kind = EMappingKind_Axis; out->leftx.target = SDL_GAMEPAD_AXIS_LEFTX; out->lefty.kind = EMappingKind_Axis; out->lefty.target = SDL_GAMEPAD_AXIS_LEFTY; out->rightx.kind = EMappingKind_Axis; out->rightx.target = SDL_GAMEPAD_AXIS_RIGHTX; out->righty.kind = EMappingKind_Axis; out->righty.target = SDL_GAMEPAD_AXIS_RIGHTY; out->lefttrigger.kind = EMappingKind_Axis; out->lefttrigger.target = SDL_GAMEPAD_AXIS_LEFT_TRIGGER; out->righttrigger.kind = EMappingKind_Axis; out->righttrigger.target = SDL_GAMEPAD_AXIS_RIGHT_TRIGGER; return true; } SDL_JoystickDriver SDL_GAMEINPUT_JoystickDriver = { GAMEINPUT_JoystickInit, GAMEINPUT_JoystickGetCount, GAMEINPUT_JoystickDetect, GAMEINPUT_JoystickIsDevicePresent, GAMEINPUT_JoystickGetDeviceName, GAMEINPUT_JoystickGetDevicePath, GAMEINPUT_JoystickGetDeviceSteamVirtualGamepadSlot, GAMEINPUT_JoystickGetDevicePlayerIndex, GAMEINPUT_JoystickSetDevicePlayerIndex, GAMEINPUT_JoystickGetDeviceGUID, GAMEINPUT_JoystickGetDeviceInstanceID, GAMEINPUT_JoystickOpen, GAMEINPUT_JoystickRumble, GAMEINPUT_JoystickRumbleTriggers, GAMEINPUT_JoystickSetLED, GAMEINPUT_JoystickSendEffect, GAMEINPUT_JoystickSetSensorsEnabled, GAMEINPUT_JoystickUpdate, GAMEINPUT_JoystickClose, GAMEINPUT_JoystickQuit, GAMEINPUT_JoystickGetGamepadMapping }; #endif // SDL_JOYSTICK_GAMEINPUT
0
0.938511
1
0.938511
game-dev
MEDIA
0.755464
game-dev
0.896225
1
0.896225
wgois/OIS
7,140
includes/OISJoyStick.h
/* The zlib/libpng License Copyright (c) 2018 Arthur Brainville Copyright (c) 2015 Andrew Fenn Copyright (c) 2005-2010 Phillip Castaneda (pjcast -- www.wreckedgames.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. */ #ifndef OIS_Joystick_H #define OIS_Joystick_H #include "OISObject.h" #include "OISEvents.h" namespace OIS { /** @remarks default sensitivity for vector3 component of joystick */ #define OIS_JOYSTICK_VECTOR3_DEFAULT 2.28f //! POV / HAT Joystick component class _OISExport Pov : public Component { public: Pov() : Component(OIS_POV), direction(0) { } static const int Centered = 0x00000000; static const int North = 0x00000001; static const int South = 0x00000010; static const int East = 0x00000100; static const int West = 0x00001000; static const int NorthEast = 0x00000101; static const int SouthEast = 0x00000110; static const int NorthWest = 0x00001001; static const int SouthWest = 0x00001010; int direction; }; //! A sliding axis - only used in Win32 Right Now class _OISExport Slider : public Component { public: Slider() : Component(OIS_Slider), abX(0), abY(0) {}; //! true if pushed, false otherwise int abX, abY; }; /** Represents the state of the joystick All members are valid for both buffered and non buffered mode Sticks with zero values are not present on the device */ class _OISExport JoyStickState { public: //! Constructor JoyStickState() { clear(); } //! Represents all the buttons (uses a bitset) std::vector<bool> mButtons; //! Represents all the single axes on the device std::vector<Axis> mAxes; //! Represents the value of a POV. Maximum of 4 Pov mPOV[4]; //! Represent the max sliders Slider mSliders[4]; //! Represents all Vector type controls the device exports std::vector<Vector3> mVectors; //! internal method to reset all variables to initial values void clear() { for(std::vector<bool>::iterator i = mButtons.begin(), e = mButtons.end(); i != e; ++i) { (*i) = false; } for(std::vector<Axis>::iterator i = mAxes.begin(), e = mAxes.end(); i != e; ++i) { i->absOnly = true; //Currently, joysticks only report Absolute values i->clear(); } for(std::vector<Vector3>::iterator i = mVectors.begin(), e = mVectors.end(); i != e; ++i) { i->clear(); } for(int i = 0; i < 4; ++i) { mPOV[i].direction = Pov::Centered; mSliders[i].abX = mSliders[i].abY = 0; } } }; /** Specialised for joystick events */ class _OISExport JoyStickEvent : public EventArg { public: JoyStickEvent(Object* obj, const JoyStickState& st) : EventArg(obj), state(st) { } virtual ~JoyStickEvent() { } const JoyStickState& state; private: // Prevent copying. JoyStickEvent(const JoyStickEvent&); JoyStickEvent& operator=(JoyStickEvent); }; /** To recieve buffered joystick input, derive a class from this, and implement the methods here. Then set the call back to your JoyStick instance with JoyStick::setEventCallback Each JoyStick instance can use the same callback class, as a devID number will be provided to differentiate between connected joysticks. Of course, each can have a seperate callback instead. */ class _OISExport JoyStickListener { public: virtual ~JoyStickListener() { } /** @remarks Joystick button down event */ virtual bool buttonPressed(const JoyStickEvent& arg, int button) = 0; /** @remarks Joystick button up event */ virtual bool buttonReleased(const JoyStickEvent& arg, int button) = 0; /** @remarks Joystick axis moved event */ virtual bool axisMoved(const JoyStickEvent& arg, int axis) = 0; //-- Not so common control events, so are not required --// //! Joystick Event, and sliderID virtual bool sliderMoved(const JoyStickEvent& arg, int index) { OIS_UNUSED(arg); OIS_UNUSED(index); return true; } //! Joystick Event, and povID virtual bool povMoved(const JoyStickEvent& arg, int index) { OIS_UNUSED(arg); OIS_UNUSED(index); return true; } //! Joystick Event, and Vector3ID virtual bool vector3Moved(const JoyStickEvent& arg, int index) { OIS_UNUSED(arg); OIS_UNUSED(index); return true; } }; /** Joystick base class. To be implemented by specific system (ie. DirectX joystick) This class is useful as you remain OS independent using this common interface. */ class _OISExport JoyStick : public Object { public: virtual ~JoyStick() { } /** @remarks Returns the number of requested components @param cType The ComponentType you are interested in knowing about */ int getNumberOfComponents(ComponentType cType) const; /** @remarks Sets a cutoff limit for changes in the Vector3 component for movement to be ignored. Helps reduce much event traffic for frequent small/sensitive changes @param degrees The degree under which Vector3 events should be discarded */ void setVector3Sensitivity(float degrees = OIS_JOYSTICK_VECTOR3_DEFAULT); /** @remarks Returns the sensitivity cutoff for Vector3 Component */ float getVector3Sensitivity() const; /** @remarks Register/unregister a JoyStick Listener - Only one allowed for simplicity. If broadcasting is neccessary, just broadcast from the callback you registered. @param joyListener Send a pointer to a class derived from JoyStickListener or 0 to clear the callback */ virtual void setEventCallback(JoyStickListener* joyListener); /** @remarks Returns currently set callback.. or null */ JoyStickListener* getEventCallback() const; /** @remarks Returns the state of the joystick - is valid for both buffered and non buffered mode */ const JoyStickState& getJoyStickState() const { return mState; } //! The minimal axis value static const int MIN_AXIS = -32768; //! The maximum axis value static const int MAX_AXIS = 32767; protected: JoyStick(const std::string& vendor, bool buffered, int devID, InputManager* creator); //! Number of sliders int mSliders; //! Number of POVs int mPOVs; //! The JoyStickState structure (contains all component values) JoyStickState mState; //! The callback listener JoyStickListener* mListener; //! Adjustment factor for orientation vector accuracy float mVector3Sensitivity; }; } #endif
0
0.8111
1
0.8111
game-dev
MEDIA
0.806758
game-dev
0.508271
1
0.508271
godotengine/godot-visual-script
71,835
visual_script_func_nodes.cpp
/**************************************************************************/ /* visual_script_func_nodes.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 "visual_script_func_nodes.h" #include "core/config/engine.h" #include "core/io/resource_loader.h" #include "core/os/os.h" #include "core/templates/local_vector.h" #include "core/variant/variant.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "visual_script_nodes.h" ////////////////////////////////////////// ////////////////CALL////////////////////// ////////////////////////////////////////// int VisualScriptFunctionCall::get_output_sequence_port_count() const { if ((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_builtin_method_const(basic_type, function))) { return 0; } else { return 1; } } bool VisualScriptFunctionCall::has_input_sequence_port() const { return !((method_cache.flags & METHOD_FLAG_CONST && call_mode != CALL_MODE_INSTANCE) || (call_mode == CALL_MODE_BASIC_TYPE && Variant::is_builtin_method_const(basic_type, function))); } #ifdef TOOLS_ENABLED static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) { if (p_edited_scene != p_current_node && p_current_node->get_owner() != p_edited_scene) { return nullptr; } Ref<Script> scr = p_current_node->get_script(); if (scr.is_valid() && scr == script) { return p_current_node; } for (int i = 0; i < p_current_node->get_child_count(); i++) { Node *n = _find_script_node(p_edited_scene, p_current_node->get_child(i), script); if (n) { return n; } } return nullptr; } #endif Node *VisualScriptFunctionCall::_get_base_node() const { #ifdef TOOLS_ENABLED Ref<Script> node_script = get_visual_script(); if (!node_script.is_valid()) { return nullptr; } MainLoop *main_loop = OS::get_singleton()->get_main_loop(); SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop); if (!scene_tree) { return nullptr; } Node *edited_scene = scene_tree->get_edited_scene_root(); if (!edited_scene) { return nullptr; } Node *script_node = _find_script_node(edited_scene, edited_scene, node_script); if (!script_node) { return nullptr; } if (!script_node->has_node(base_path)) { return nullptr; } Node *path_to = script_node->get_node(base_path); return path_to; #else return nullptr; #endif } StringName VisualScriptFunctionCall::_get_base_type() const { if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) { return get_visual_script()->get_instance_base_type(); } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) { Node *path = _get_base_node(); if (path) { return path->get_class(); } } return base_type; } int VisualScriptFunctionCall::get_input_value_port_count() const { if (call_mode == CALL_MODE_BASIC_TYPE) { Vector<Variant::Type> types; int argc = Variant::get_builtin_method_argument_count(basic_type, function); for (int i = 0; i < argc; i++) { types.push_back( Variant::get_builtin_method_argument_type(basic_type, function, i)); } return types.size() + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) + 1; } else { MethodBind *mb = ClassDB::get_method(_get_base_type(), function); if (mb) { int defaulted_args = mb->get_argument_count() < use_default_args ? mb->get_argument_count() : use_default_args; return mb->get_argument_count() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args; } int defaulted_args = method_cache.arguments.size() < use_default_args ? method_cache.arguments.size() : use_default_args; return method_cache.arguments.size() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - defaulted_args; } } int VisualScriptFunctionCall::get_output_value_port_count() const { if (call_mode == CALL_MODE_BASIC_TYPE) { bool returns = Variant::has_builtin_method_return_value(basic_type, function); return returns ? 1 : 0; } else { int ret; MethodBind *mb = ClassDB::get_method(_get_base_type(), function); if (mb) { ret = mb->has_return() ? 1 : 0; } else { ret = 1; // it is assumed that script always returns something } if (call_mode == CALL_MODE_INSTANCE) { ret++; } return ret; } } String VisualScriptFunctionCall::get_output_sequence_port_text(int p_port) const { return String(); } PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) const { if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) { if (p_idx == 0) { PropertyInfo pi; pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type); pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower()); return pi; } else { p_idx--; } } if (rpc_call_mode >= RPC_RELIABLE_TO_ID) { if (p_idx == 0) { return PropertyInfo(Variant::INT, "peer_id"); } else { p_idx--; } } #ifdef DEBUG_METHODS_ENABLED if (call_mode == CALL_MODE_BASIC_TYPE) { return PropertyInfo( Variant::get_builtin_method_argument_type(basic_type, function, p_idx), Variant::get_builtin_method_argument_name(basic_type, function, p_idx)); } else { MethodBind *mb = ClassDB::get_method(_get_base_type(), function); if (mb) { return mb->get_argument_info(p_idx); } if (p_idx >= 0 && p_idx < method_cache.arguments.size()) { return method_cache.arguments[p_idx]; } return PropertyInfo(); } #else return PropertyInfo(); #endif } PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) const { #ifdef DEBUG_METHODS_ENABLED if (call_mode == CALL_MODE_BASIC_TYPE) { return PropertyInfo( Variant::get_builtin_method_return_type(basic_type, function), ""); } else { if (call_mode == CALL_MODE_INSTANCE) { if (p_idx == 0) { return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type()); } else { p_idx--; } } PropertyInfo ret; /*MethodBind *mb = ClassDB::get_method(_get_base_type(),function); if (mb) { ret = mb->get_argument_info(-1); } else {*/ ret = method_cache.return_val; //} if (call_mode == CALL_MODE_INSTANCE) { ret.name = "return"; } else { ret.name = ""; } return ret; } #else return PropertyInfo(); #endif } String VisualScriptFunctionCall::get_caption() const { return " " + String(function) + "()"; } String VisualScriptFunctionCall::get_text() const { String text; if (call_mode == CALL_MODE_BASIC_TYPE) { text = vformat(RTR("On %s"), Variant::get_type_name(basic_type)); } else if (call_mode == CALL_MODE_INSTANCE) { text = vformat(RTR("On %s"), base_type); } else if (call_mode == CALL_MODE_NODE_PATH) { text = "[" + String(base_path.simplified()) + "]"; } else if (call_mode == CALL_MODE_SELF) { text = RTR("On Self"); } else if (call_mode == CALL_MODE_SINGLETON) { text = String(singleton) + ":" + String(function) + "()"; } if (rpc_call_mode) { text += " RPC"; if (rpc_call_mode == RPC_UNRELIABLE || rpc_call_mode == RPC_UNRELIABLE_TO_ID) { text += " UNREL"; } } return text; } void VisualScriptFunctionCall::set_basic_type(Variant::Type p_type) { if (basic_type == p_type) { return; } basic_type = p_type; notify_property_list_changed(); ports_changed_notify(); } Variant::Type VisualScriptFunctionCall::get_basic_type() const { return basic_type; } void VisualScriptFunctionCall::set_base_type(const StringName &p_type) { if (base_type == p_type) { return; } base_type = p_type; notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptFunctionCall::get_base_type() const { return base_type; } void VisualScriptFunctionCall::set_base_script(const String &p_path) { if (base_script == p_path) { return; } base_script = p_path; notify_property_list_changed(); ports_changed_notify(); } String VisualScriptFunctionCall::get_base_script() const { return base_script; } void VisualScriptFunctionCall::set_singleton(const StringName &p_type) { if (singleton == p_type) { return; } singleton = p_type; Object *obj = Engine::get_singleton()->get_singleton_object(singleton); if (obj) { base_type = obj->get_class(); } notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptFunctionCall::get_singleton() const { return singleton; } void VisualScriptFunctionCall::_update_method_cache() { StringName type; Ref<Script> method_cache_script; if (call_mode == CALL_MODE_NODE_PATH) { Node *node = _get_base_node(); if (node) { type = node->get_class(); base_type = type; // cache, too method_cache_script = node->get_script(); } } else if (call_mode == CALL_MODE_SELF) { if (get_visual_script().is_valid()) { type = get_visual_script()->get_instance_base_type(); base_type = type; // cache, too method_cache_script = get_visual_script(); } } else if (call_mode == CALL_MODE_SINGLETON) { Object *obj = Engine::get_singleton()->get_singleton_object(singleton); if (obj) { type = obj->get_class(); method_cache_script = obj->get_script(); } } else if (call_mode == CALL_MODE_INSTANCE) { type = base_type; if (!base_script.is_empty()) { if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) { ScriptServer::edit_request_func(base_script); // make sure it's loaded } if (ResourceCache::has(base_script)) { method_cache_script = ResourceCache::get_ref(base_script); } else { return; } } } MethodBind *mb = ClassDB::get_method(type, function); if (mb) { use_default_args = mb->get_default_argument_count(); method_cache = MethodInfo(); for (int i = 0; i < mb->get_argument_count(); i++) { #ifdef DEBUG_METHODS_ENABLED method_cache.arguments.push_back(mb->get_argument_info(i)); #else method_cache.arguments.push_back(PropertyInfo()); #endif } if (mb->is_const()) { method_cache.flags |= METHOD_FLAG_CONST; } #ifdef DEBUG_METHODS_ENABLED method_cache.return_val = mb->get_return_info(); #endif if (mb->is_vararg()) { // for vararg just give it 10 arguments (should be enough for most use // cases) for (int i = 0; i < 10; i++) { method_cache.arguments.push_back( PropertyInfo(Variant::NIL, "arg" + itos(i))); use_default_args++; } } } else if (method_cache_script.is_valid() && method_cache_script->has_method(function)) { method_cache = method_cache_script->get_method_info(function); use_default_args = method_cache.default_arguments.size(); } } void VisualScriptFunctionCall::set_function(const StringName &p_type) { if (function == p_type) { return; } function = p_type; if (call_mode == CALL_MODE_BASIC_TYPE) { use_default_args = Variant::get_builtin_method_default_arguments(basic_type, function) .size(); } else { // update all caches _update_method_cache(); } notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptFunctionCall::get_function() const { return function; } void VisualScriptFunctionCall::set_base_path(const NodePath &p_type) { if (base_path == p_type) { return; } base_path = p_type; notify_property_list_changed(); ports_changed_notify(); } NodePath VisualScriptFunctionCall::get_base_path() const { return base_path; } void VisualScriptFunctionCall::set_call_mode(CallMode p_mode) { if (call_mode == p_mode) { return; } call_mode = p_mode; notify_property_list_changed(); ports_changed_notify(); } VisualScriptFunctionCall::CallMode VisualScriptFunctionCall::get_call_mode() const { return call_mode; } void VisualScriptFunctionCall::set_use_default_args(int p_amount) { if (use_default_args == p_amount) { return; } use_default_args = p_amount; ports_changed_notify(); } void VisualScriptFunctionCall::set_rpc_call_mode( VisualScriptFunctionCall::RPCCallMode p_mode) { if (rpc_call_mode == p_mode) { return; } rpc_call_mode = p_mode; ports_changed_notify(); notify_property_list_changed(); } VisualScriptFunctionCall::RPCCallMode VisualScriptFunctionCall::get_rpc_call_mode() const { return rpc_call_mode; } int VisualScriptFunctionCall::get_use_default_args() const { return use_default_args; } void VisualScriptFunctionCall::set_validate(bool p_amount) { validate = p_amount; } bool VisualScriptFunctionCall::get_validate() const { return validate; } void VisualScriptFunctionCall::_set_argument_cache(const Dictionary &p_cache) { // so everything works in case all else fails method_cache = MethodInfo::from_dict(p_cache); } Dictionary VisualScriptFunctionCall::_get_argument_cache() const { return method_cache; } void VisualScriptFunctionCall::_validate_property( PropertyInfo &p_property) const { if (p_property.name == "base_type") { if (call_mode != CALL_MODE_INSTANCE) { p_property.usage = PROPERTY_USAGE_NO_EDITOR; } else { p_property.hint = PROPERTY_HINT_TYPE_STRING; p_property.hint_string = "Object"; } } if (p_property.name == "base_script") { if (call_mode != CALL_MODE_INSTANCE) { p_property.usage = PROPERTY_USAGE_NONE; } else { p_property.hint = PROPERTY_HINT_FILE; p_property.hint_string = "*.gd,*.vs"; } } if (p_property.name == "basic_type") { if (call_mode != CALL_MODE_BASIC_TYPE) { p_property.usage = PROPERTY_USAGE_NONE; } else { p_property.hint = PROPERTY_HINT_ENUM; p_property.hint_string = Variant::get_type_name(Variant::NIL); } } if (p_property.name == "singleton") { if (call_mode != CALL_MODE_SINGLETON) { p_property.usage = PROPERTY_USAGE_NONE; } else { List<Engine::Singleton> names; Engine::get_singleton()->get_singletons(&names); p_property.hint = PROPERTY_HINT_ENUM; String sl; for (const Engine::Singleton &E : names) { if (!sl.is_empty()) { sl += ","; } sl += E.name; } p_property.hint_string = sl; } } if (p_property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { p_property.usage = PROPERTY_USAGE_NONE; } else { Node *bnode = _get_base_node(); if (bnode) { p_property.hint_string = bnode->get_path(); } } } if (p_property.name == "rpc_call_mode") { if (call_mode == CALL_MODE_BASIC_TYPE) { p_property.usage = PROPERTY_USAGE_NONE; } else { p_property.hint = PROPERTY_HINT_ENUM; p_property.hint_string = "Disabled,Remote Procedure Call,Sync,Master,Slave"; } } } void VisualScriptFunctionCall::_bind_methods() { ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptFunctionCall::set_base_type); ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptFunctionCall::get_base_type); ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptFunctionCall::set_base_script); ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptFunctionCall::get_base_script); ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptFunctionCall::set_basic_type); ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptFunctionCall::get_basic_type); ClassDB::bind_method(D_METHOD("set_singleton", "singleton"), &VisualScriptFunctionCall::set_singleton); ClassDB::bind_method(D_METHOD("get_singleton"), &VisualScriptFunctionCall::get_singleton); ClassDB::bind_method(D_METHOD("set_function", "function"), &VisualScriptFunctionCall::set_function); ClassDB::bind_method(D_METHOD("get_function"), &VisualScriptFunctionCall::get_function); ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptFunctionCall::set_call_mode); ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptFunctionCall::get_call_mode); ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptFunctionCall::set_base_path); ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptFunctionCall::get_base_path); ClassDB::bind_method(D_METHOD("set_use_default_args", "amount"), &VisualScriptFunctionCall::set_use_default_args); ClassDB::bind_method(D_METHOD("get_use_default_args"), &VisualScriptFunctionCall::get_use_default_args); ClassDB::bind_method(D_METHOD("_set_argument_cache", "argument_cache"), &VisualScriptFunctionCall::_set_argument_cache); ClassDB::bind_method(D_METHOD("_get_argument_cache"), &VisualScriptFunctionCall::_get_argument_cache); ClassDB::bind_method(D_METHOD("set_rpc_call_mode", "mode"), &VisualScriptFunctionCall::set_rpc_call_mode); ClassDB::bind_method(D_METHOD("get_rpc_call_mode"), &VisualScriptFunctionCall::get_rpc_call_mode); ClassDB::bind_method(D_METHOD("set_validate", "enable"), &VisualScriptFunctionCall::set_validate); ClassDB::bind_method(D_METHOD("get_validate"), &VisualScriptFunctionCall::get_validate); String bt; for (int i = 0; i < Variant::VARIANT_MAX; i++) { if (i > 0) { bt += ","; } bt += Variant::get_type_name(Variant::Type(i)); } List<String> script_extensions; for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->get_recognized_extensions( &script_extensions); } String script_ext_hint; for (const String &E : script_extensions) { if (!script_ext_hint.is_empty()) { script_ext_hint += ","; } script_ext_hint += "*." + E; } ADD_PROPERTY(PropertyInfo(Variant::INT, "call_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type,Singleton"), "set_call_mode", "get_call_mode"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "singleton"), "set_singleton", "get_singleton"); ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type"); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path"); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "argument_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_argument_cache", "_get_argument_cache"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "function"), "set_function", "get_function"); // when set, if loaded properly, will override // argument count. ADD_PROPERTY(PropertyInfo(Variant::INT, "use_default_args"), "set_use_default_args", "get_use_default_args"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "validate"), "set_validate", "get_validate"); ADD_PROPERTY( PropertyInfo(Variant::INT, "rpc_call_mode", PROPERTY_HINT_ENUM, "Disabled,Reliable,Unreliable,ReliableToID,UnreliableToID"), "set_rpc_call_mode", "get_rpc_call_mode"); // when set, if loaded properly, will override // argument count. BIND_ENUM_CONSTANT(CALL_MODE_SELF); BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH); BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE); BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE); BIND_ENUM_CONSTANT(CALL_MODE_SINGLETON); BIND_ENUM_CONSTANT(RPC_DISABLED); BIND_ENUM_CONSTANT(RPC_RELIABLE); BIND_ENUM_CONSTANT(RPC_UNRELIABLE); BIND_ENUM_CONSTANT(RPC_RELIABLE_TO_ID); BIND_ENUM_CONSTANT(RPC_UNRELIABLE_TO_ID); } class VisualScriptNodeInstanceFunctionCall : public VisualScriptNodeInstance { public: VisualScriptFunctionCall::CallMode call_mode; NodePath node_path; int input_args = 0; bool validate = false; int returns = 0; VisualScriptFunctionCall::RPCCallMode rpc_mode; StringName function; StringName singleton; VisualScriptFunctionCall *node = nullptr; VisualScriptInstance *instance = nullptr; // virtual int get_working_memory_size() const override { return 0; } // virtual bool is_output_port_unsequenced(int p_idx) const { return false; } // virtual bool get_output_port_unsequenced(int p_idx,Variant* // r_value,Variant* p_working_mem,String &r_error) const { return true; } _FORCE_INLINE_ bool call_rpc(Object *p_base, const Variant **p_args, int p_argcount) { if (!p_base) { return false; } Node *call_rpc_node = Object::cast_to<Node>(p_base); if (!call_rpc_node) { return false; } int to_id = 0; // bool reliable = true; if (rpc_mode >= VisualScriptFunctionCall::RPC_RELIABLE_TO_ID) { to_id = *p_args[0]; p_args += 1; p_argcount -= 1; // if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE_TO_ID) { // reliable = false; // } } // else if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE) { // reliable = false; // } // TODO reliable? call_rpc_node->rpcp(to_id, function, p_args, p_argcount); return true; } virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (call_mode) { case VisualScriptFunctionCall::CALL_MODE_SELF: { Object *object = instance->get_owner_ptr(); if (rpc_mode) { call_rpc(object, p_inputs, input_args); } else if (returns) { *p_outputs[0] = object->callp(function, p_inputs, input_args, r_error); } else { object->callp(function, p_inputs, input_args, r_error); } } break; case VisualScriptFunctionCall::CALL_MODE_NODE_PATH: { Node *call_node = Object::cast_to<Node>(instance->get_owner_ptr()); if (!call_node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Base object is not a Node!"; return 0; } Node *another = call_node->get_node(node_path); if (!another) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Path does not lead Node!"; return 0; } if (rpc_mode) { call_rpc(call_node, p_inputs, input_args); } else if (returns) { *p_outputs[0] = another->callp(function, p_inputs, input_args, r_error); } else { another->callp(function, p_inputs, input_args, r_error); } } break; case VisualScriptFunctionCall::CALL_MODE_INSTANCE: case VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE: { Variant v = *p_inputs[0]; if (rpc_mode) { Object *obj = v; if (obj) { call_rpc(obj, p_inputs + 1, input_args - 1); } } else if (returns) { if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) { if (returns >= 2) { v.callp(function, p_inputs + 1, input_args, *p_outputs[1], r_error); } else if (returns == 1) { Variant ret; v.callp(function, p_inputs + 1, input_args, ret, r_error); } else { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid returns count for call_mode == CALL_MODE_INSTANCE"; return 0; } } else { v.callp(function, p_inputs + 1, input_args, *p_outputs[0], r_error); } } else { Variant ret; v.callp(function, p_inputs + 1, input_args, ret, r_error); } if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) { *p_outputs[0] = *p_inputs[0]; } } break; case VisualScriptFunctionCall::CALL_MODE_SINGLETON: { Object *object = Engine::get_singleton()->get_singleton_object(singleton); if (!object) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid singleton name: '" + String(singleton) + "'"; return 0; } if (rpc_mode) { call_rpc(object, p_inputs, input_args); } else if (returns) { *p_outputs[0] = object->callp(function, p_inputs, input_args, r_error); } else { object->callp(function, p_inputs, input_args, r_error); } } break; } if (!validate) { // ignore call errors if validation is disabled r_error.error = Callable::CallError::CALL_OK; r_error_str = String(); } return 0; } }; VisualScriptNodeInstance * VisualScriptFunctionCall::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceFunctionCall *instance = memnew(VisualScriptNodeInstanceFunctionCall); instance->node = this; instance->instance = p_instance; instance->singleton = singleton; instance->function = function; instance->call_mode = call_mode; instance->returns = get_output_value_port_count(); instance->node_path = base_path; instance->input_args = get_input_value_port_count() - ((call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0); instance->rpc_mode = rpc_call_mode; instance->validate = validate; return instance; } VisualScriptFunctionCall::TypeGuess VisualScriptFunctionCall::guess_output_type(TypeGuess *p_inputs, int p_output) const { if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) { return p_inputs[0]; } return VisualScriptNode::guess_output_type(p_inputs, p_output); } VisualScriptFunctionCall::VisualScriptFunctionCall() { validate = true; call_mode = CALL_MODE_SELF; basic_type = Variant::NIL; use_default_args = 0; base_type = "Object"; rpc_call_mode = RPC_DISABLED; } template <VisualScriptFunctionCall::CallMode cmode> static Ref<VisualScriptNode> create_function_call_node(const String &p_name) { Ref<VisualScriptFunctionCall> node; node.instantiate(); node->set_call_mode(cmode); return node; } ////////////////////////////////////////// ////////////////SET////////////////////// ////////////////////////////////////////// int VisualScriptPropertySet::get_output_sequence_port_count() const { return 1; } bool VisualScriptPropertySet::has_input_sequence_port() const { return true; } Node *VisualScriptPropertySet::_get_base_node() const { #ifdef TOOLS_ENABLED Ref<Script> set_node_script = get_visual_script(); if (!set_node_script.is_valid()) { return nullptr; } MainLoop *main_loop = OS::get_singleton()->get_main_loop(); SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop); if (!scene_tree) { return nullptr; } Node *edited_scene = scene_tree->get_edited_scene_root(); if (!edited_scene) { return nullptr; } Node *script_node = _find_script_node(edited_scene, edited_scene, set_node_script); if (!script_node) { return nullptr; } if (!script_node->has_node(base_path)) { return nullptr; } Node *path_to = script_node->get_node(base_path); return path_to; #else return nullptr; #endif } StringName VisualScriptPropertySet::_get_base_type() const { if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) { return get_visual_script()->get_instance_base_type(); } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) { Node *path = _get_base_node(); if (path) { return path->get_class(); } } return base_type; } int VisualScriptPropertySet::get_input_value_port_count() const { int pc = (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 2 : 1; return pc; } int VisualScriptPropertySet::get_output_value_port_count() const { return (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0; } String VisualScriptPropertySet::get_output_sequence_port_text(int p_port) const { return String(); } void VisualScriptPropertySet::_adjust_input_index(PropertyInfo &pinfo) const { if (index != StringName()) { Variant v; Callable::CallError ce; Variant::construct(pinfo.type, v, nullptr, 0, ce); Variant i = v.get(index); pinfo.type = i.get_type(); } } PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const { if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) { if (p_idx == 0) { PropertyInfo pi; pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type); pi.name = "instance"; return pi; } } List<PropertyInfo> props; ClassDB::get_property_list(_get_base_type(), &props, false); for (const PropertyInfo &E : props) { if (E.name == property) { String detail_prop_name = property; if (index != StringName()) { detail_prop_name += "." + String(index); } PropertyInfo pinfo = PropertyInfo(E.type, detail_prop_name, E.hint, E.hint_string); _adjust_input_index(pinfo); return pinfo; } } PropertyInfo pinfo = type_cache; _adjust_input_index(pinfo); return pinfo; } PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) const { if (call_mode == CALL_MODE_BASIC_TYPE) { return PropertyInfo(basic_type, "pass"); } else if (call_mode == CALL_MODE_INSTANCE) { return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type()); } else { return PropertyInfo(); } } String VisualScriptPropertySet::get_caption() const { static const LocalVector<String> opname = { RTR("Set %s"), RTR("Add %s"), RTR("Subtract %s"), RTR("Multiply %s"), RTR("Divide %s"), RTR("Mod %s"), RTR("ShiftLeft %s"), RTR("ShiftRight %s"), RTR("BitAnd %s"), RTR("BitOr %s"), RTR("BitXor %s"), }; String prop = property; if (index != StringName()) { prop += "." + String(index); } return vformat(opname[assign_op], prop); } String VisualScriptPropertySet::get_text() const { if (!has_input_sequence_port()) { return ""; } if (call_mode == CALL_MODE_BASIC_TYPE) { return vformat(RTR("On %s"), Variant::get_type_name(basic_type)); } else if (call_mode == CALL_MODE_INSTANCE) { return vformat(RTR("On %s"), base_type); } else if (call_mode == CALL_MODE_NODE_PATH) { return " [" + String(base_path.simplified()) + "]"; } else { return RTR("On Self"); } } void VisualScriptPropertySet::_update_base_type() { // cache it because this information may not be available on load if (call_mode == CALL_MODE_NODE_PATH) { Node *node = _get_base_node(); if (node) { base_type = node->get_class(); } } else if (call_mode == CALL_MODE_SELF) { if (get_visual_script().is_valid()) { base_type = get_visual_script()->get_instance_base_type(); } } } void VisualScriptPropertySet::set_basic_type(Variant::Type p_type) { if (basic_type == p_type) { return; } basic_type = p_type; notify_property_list_changed(); _update_base_type(); ports_changed_notify(); } Variant::Type VisualScriptPropertySet::get_basic_type() const { return basic_type; } void VisualScriptPropertySet::set_base_type(const StringName &p_type) { if (base_type == p_type) { return; } base_type = p_type; notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptPropertySet::get_base_type() const { return base_type; } void VisualScriptPropertySet::set_base_script(const String &p_path) { if (base_script == p_path) { return; } base_script = p_path; notify_property_list_changed(); ports_changed_notify(); } String VisualScriptPropertySet::get_base_script() const { return base_script; } void VisualScriptPropertySet::_update_cache() { if (!Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop())) { return; } if (!Engine::get_singleton() ->is_editor_hint()) { // only update cache if editor exists, it's // pointless otherwise return; } if (call_mode == CALL_MODE_BASIC_TYPE) { // not super efficient.. Variant v; Callable::CallError ce; Variant::construct(basic_type, v, nullptr, 0, ce); List<PropertyInfo> pinfo; v.get_property_list(&pinfo); for (const PropertyInfo &E : pinfo) { if (E.name == property) { type_cache = E; } } } else { StringName type; Ref<Script> call_non_basic_script; Node *node = nullptr; if (call_mode == CALL_MODE_NODE_PATH) { node = _get_base_node(); if (node) { type = node->get_class(); base_type = type; // cache, too call_non_basic_script = node->get_script(); } } else if (call_mode == CALL_MODE_SELF) { if (get_visual_script().is_valid()) { type = get_visual_script()->get_instance_base_type(); base_type = type; // cache, too call_non_basic_script = get_visual_script(); } } else if (call_mode == CALL_MODE_INSTANCE) { type = base_type; if (!base_script.is_empty()) { if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) { ScriptServer::edit_request_func(base_script); // make sure it's loaded } if (ResourceCache::has(base_script)) { call_non_basic_script = ResourceCache::get_ref(base_script); } else { return; } } } List<PropertyInfo> pinfo; if (node) { node->get_property_list(&pinfo); } else { ClassDB::get_property_list(type, &pinfo); } if (call_non_basic_script.is_valid()) { call_non_basic_script->get_script_property_list(&pinfo); } for (const PropertyInfo &E : pinfo) { if (E.name == property) { type_cache = E; return; } } } } void VisualScriptPropertySet::set_property(const StringName &p_type) { if (property == p_type) { return; } property = p_type; index = StringName(); _update_cache(); notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptPropertySet::get_property() const { return property; } void VisualScriptPropertySet::set_base_path(const NodePath &p_type) { if (base_path == p_type) { return; } base_path = p_type; _update_base_type(); notify_property_list_changed(); ports_changed_notify(); } NodePath VisualScriptPropertySet::get_base_path() const { return base_path; } void VisualScriptPropertySet::set_call_mode(CallMode p_mode) { if (call_mode == p_mode) { return; } call_mode = p_mode; _update_base_type(); notify_property_list_changed(); ports_changed_notify(); } VisualScriptPropertySet::CallMode VisualScriptPropertySet::get_call_mode() const { return call_mode; } void VisualScriptPropertySet::_set_type_cache(const Dictionary &p_type) { type_cache = PropertyInfo::from_dict(p_type); } Dictionary VisualScriptPropertySet::_get_type_cache() const { return type_cache; } void VisualScriptPropertySet::set_index(const StringName &p_type) { if (index == p_type) { return; } index = p_type; _update_cache(); notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptPropertySet::get_index() const { return index; } void VisualScriptPropertySet::set_assign_op(AssignOp p_op) { ERR_FAIL_INDEX(p_op, ASSIGN_OP_MAX); if (assign_op == p_op) { return; } assign_op = p_op; _update_cache(); notify_property_list_changed(); ports_changed_notify(); } VisualScriptPropertySet::AssignOp VisualScriptPropertySet::get_assign_op() const { return assign_op; } void VisualScriptPropertySet::_validate_property( PropertyInfo &p_property) const { if (p_property.name == "base_type") { if (call_mode != CALL_MODE_INSTANCE) { p_property.usage = PROPERTY_USAGE_NO_EDITOR; } } if (p_property.name == "base_script") { if (call_mode != CALL_MODE_INSTANCE) { p_property.usage = PROPERTY_USAGE_NONE; } } if (p_property.name == "basic_type") { if (call_mode != CALL_MODE_BASIC_TYPE) { p_property.usage = PROPERTY_USAGE_NONE; } } if (p_property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { p_property.usage = PROPERTY_USAGE_NONE; } else { Node *bnode = _get_base_node(); if (bnode) { p_property.hint_string = bnode->get_path(); // convert to long string } } } if (p_property.name == "index") { Callable::CallError ce; Variant v; Variant::construct(type_cache.type, v, nullptr, 0, ce); List<PropertyInfo> plist; v.get_property_list(&plist); String options = ""; for (const PropertyInfo &E : plist) { options += "," + E.name; } p_property.hint = PROPERTY_HINT_ENUM; p_property.hint_string = options; p_property.type = Variant::STRING; if (options.is_empty()) { p_property.usage = PROPERTY_USAGE_NONE; // hide if type has no usable // index } } } void VisualScriptPropertySet::_bind_methods() { ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptPropertySet::set_base_type); ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptPropertySet::get_base_type); ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptPropertySet::set_base_script); ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptPropertySet::get_base_script); ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptPropertySet::set_basic_type); ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptPropertySet::get_basic_type); ClassDB::bind_method(D_METHOD("_set_type_cache", "type_cache"), &VisualScriptPropertySet::_set_type_cache); ClassDB::bind_method(D_METHOD("_get_type_cache"), &VisualScriptPropertySet::_get_type_cache); ClassDB::bind_method(D_METHOD("set_property", "property"), &VisualScriptPropertySet::set_property); ClassDB::bind_method(D_METHOD("get_property"), &VisualScriptPropertySet::get_property); ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptPropertySet::set_call_mode); ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptPropertySet::get_call_mode); ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptPropertySet::set_base_path); ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptPropertySet::get_base_path); ClassDB::bind_method(D_METHOD("set_index", "index"), &VisualScriptPropertySet::set_index); ClassDB::bind_method(D_METHOD("get_index"), &VisualScriptPropertySet::get_index); ClassDB::bind_method(D_METHOD("set_assign_op", "assign_op"), &VisualScriptPropertySet::set_assign_op); ClassDB::bind_method(D_METHOD("get_assign_op"), &VisualScriptPropertySet::get_assign_op); String bt; for (int i = 0; i < Variant::VARIANT_MAX; i++) { if (i > 0) { bt += ","; } bt += Variant::get_type_name(Variant::Type(i)); } List<String> script_extensions; for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->get_recognized_extensions( &script_extensions); } String script_ext_hint; for (const String &E : script_extensions) { if (!script_ext_hint.is_empty()) { script_ext_hint += ","; } script_ext_hint += "*." + E; } ADD_PROPERTY(PropertyInfo(Variant::INT, "set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script"); ADD_PROPERTY(PropertyInfo(Variant::INT, "type_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_type_cache", "_get_type_cache"); ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type"); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "property"), "set_property", "get_property"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "index"), "set_index", "get_index"); ADD_PROPERTY(PropertyInfo(Variant::INT, "assign_op", PROPERTY_HINT_ENUM, "Assign,Add,Sub,Mul,Div,Mod,ShiftLeft,ShiftRight," "BitAnd,BitOr,Bitxor"), "set_assign_op", "get_assign_op"); BIND_ENUM_CONSTANT(CALL_MODE_SELF); BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH); BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE); BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE); BIND_ENUM_CONSTANT(ASSIGN_OP_NONE); BIND_ENUM_CONSTANT(ASSIGN_OP_ADD); BIND_ENUM_CONSTANT(ASSIGN_OP_SUB); BIND_ENUM_CONSTANT(ASSIGN_OP_MUL); BIND_ENUM_CONSTANT(ASSIGN_OP_DIV); BIND_ENUM_CONSTANT(ASSIGN_OP_MOD); BIND_ENUM_CONSTANT(ASSIGN_OP_SHIFT_LEFT); BIND_ENUM_CONSTANT(ASSIGN_OP_SHIFT_RIGHT); BIND_ENUM_CONSTANT(ASSIGN_OP_BIT_AND); BIND_ENUM_CONSTANT(ASSIGN_OP_BIT_OR); BIND_ENUM_CONSTANT(ASSIGN_OP_BIT_XOR); } class VisualScriptNodeInstancePropertySet : public VisualScriptNodeInstance { public: VisualScriptPropertySet::CallMode call_mode; NodePath node_path; StringName property; VisualScriptPropertySet *node = nullptr; VisualScriptInstance *instance = nullptr; VisualScriptPropertySet::AssignOp assign_op; StringName index; bool needs_get = false; // virtual int get_working_memory_size() const override { return 0; } // virtual bool is_output_port_unsequenced(int p_idx) const { return false; } // virtual bool get_output_port_unsequenced(int p_idx,Variant* // r_value,Variant* p_working_mem,String &r_error) const { return true; } _FORCE_INLINE_ void _process_get(Variant &source, const Variant &p_argument, bool &valid) { if (index != StringName() && assign_op == VisualScriptPropertySet::ASSIGN_OP_NONE) { source.set_named(index, p_argument, valid); } else { Variant value; if (index != StringName()) { value = source.get_named(index, valid); } else { value = source; } switch (assign_op) { case VisualScriptPropertySet::ASSIGN_OP_NONE: { // should never get here } break; case VisualScriptPropertySet::ASSIGN_OP_ADD: { value = Variant::evaluate(Variant::OP_ADD, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_SUB: { value = Variant::evaluate(Variant::OP_SUBTRACT, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_MUL: { value = Variant::evaluate(Variant::OP_MULTIPLY, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_DIV: { value = Variant::evaluate(Variant::OP_DIVIDE, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_MOD: { value = Variant::evaluate(Variant::OP_MODULE, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_SHIFT_LEFT: { value = Variant::evaluate(Variant::OP_SHIFT_LEFT, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_SHIFT_RIGHT: { value = Variant::evaluate(Variant::OP_SHIFT_RIGHT, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_BIT_AND: { value = Variant::evaluate(Variant::OP_BIT_AND, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_BIT_OR: { value = Variant::evaluate(Variant::OP_BIT_OR, value, p_argument); } break; case VisualScriptPropertySet::ASSIGN_OP_BIT_XOR: { value = Variant::evaluate(Variant::OP_BIT_XOR, value, p_argument); } break; default: { } } if (index != StringName()) { source.set_named(index, value, valid); } else { source = value; } } } virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (call_mode) { case VisualScriptPropertySet::CALL_MODE_SELF: { Object *object = instance->get_owner_ptr(); bool valid; if (needs_get) { Variant value = object->get(property, &valid); _process_get(value, *p_inputs[0], valid); object->set(property, value, &valid); } else { object->set(property, *p_inputs[0], &valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid set value '" + String(*p_inputs[0]) + "' on property '" + String(property) + "' of type " + object->get_class(); } } break; case VisualScriptPropertySet::CALL_MODE_NODE_PATH: { Node *instance_call_mode_node = Object::cast_to<Node>(instance->get_owner_ptr()); if (!instance_call_mode_node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Base object is not a Node!"; return 0; } Node *another = instance_call_mode_node->get_node(node_path); if (!another) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Path does not lead Node!"; return 0; } bool valid; if (needs_get) { Variant value = another->get(property, &valid); _process_get(value, *p_inputs[0], valid); another->set(property, value, &valid); } else { another->set(property, *p_inputs[0], &valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid set value '" + String(*p_inputs[0]) + "' on property '" + String(property) + "' of type " + another->get_class(); } } break; case VisualScriptPropertySet::CALL_MODE_INSTANCE: case VisualScriptPropertySet::CALL_MODE_BASIC_TYPE: { Variant v = *p_inputs[0]; bool valid; if (needs_get) { Variant value = v.get_named(property, valid); _process_get(value, *p_inputs[1], valid); v.set_named(property, value, valid); } else { v.set_named(property, *p_inputs[1], valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid set value '" + String(*p_inputs[1]) + "' (" + Variant::get_type_name(p_inputs[1]->get_type()) + ") on property '" + String(property) + "' of type " + Variant::get_type_name(v.get_type()); } *p_outputs[0] = v; } break; } return 0; } }; VisualScriptNodeInstance * VisualScriptPropertySet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstancePropertySet *instance = memnew(VisualScriptNodeInstancePropertySet); instance->node = this; instance->instance = p_instance; instance->property = property; instance->call_mode = call_mode; instance->node_path = base_path; instance->assign_op = assign_op; instance->index = index; instance->needs_get = index != StringName() || assign_op != ASSIGN_OP_NONE; return instance; } VisualScriptPropertySet::TypeGuess VisualScriptPropertySet::guess_output_type(TypeGuess *p_inputs, int p_output) const { if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) { return p_inputs[0]; } return VisualScriptNode::guess_output_type(p_inputs, p_output); } VisualScriptPropertySet::VisualScriptPropertySet() { assign_op = ASSIGN_OP_NONE; call_mode = CALL_MODE_SELF; base_type = "Object"; basic_type = Variant::NIL; } template <VisualScriptPropertySet::CallMode cmode> static Ref<VisualScriptNode> create_property_set_node(const String &p_name) { Ref<VisualScriptPropertySet> node; node.instantiate(); node->set_call_mode(cmode); return node; } ////////////////////////////////////////// ////////////////GET////////////////////// ////////////////////////////////////////// int VisualScriptPropertyGet::get_output_sequence_port_count() const { return 0; // (call_mode==CALL_MODE_SELF || // call_mode==CALL_MODE_NODE_PATH)?0:1; } bool VisualScriptPropertyGet::has_input_sequence_port() const { return false; //(call_mode==CALL_MODE_SELF || // call_mode==CALL_MODE_NODE_PATH)?false:true; } void VisualScriptPropertyGet::_update_base_type() { // cache it because this information may not be available on load if (call_mode == CALL_MODE_NODE_PATH) { Node *node = _get_base_node(); if (node) { base_type = node->get_class(); } } else if (call_mode == CALL_MODE_SELF) { if (get_visual_script().is_valid()) { base_type = get_visual_script()->get_instance_base_type(); } } } Node *VisualScriptPropertyGet::_get_base_node() const { #ifdef TOOLS_ENABLED Ref<Script> get_node_script = get_visual_script(); if (!get_node_script.is_valid()) { return nullptr; } MainLoop *main_loop = OS::get_singleton()->get_main_loop(); SceneTree *scene_tree = Object::cast_to<SceneTree>(main_loop); if (!scene_tree) { return nullptr; } Node *edited_scene = scene_tree->get_edited_scene_root(); if (!edited_scene) { return nullptr; } Node *script_node = _find_script_node(edited_scene, edited_scene, get_node_script); if (!script_node) { return nullptr; } if (!script_node->has_node(base_path)) { return nullptr; } Node *path_to = script_node->get_node(base_path); return path_to; #else return nullptr; #endif } StringName VisualScriptPropertyGet::_get_base_type() const { if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) { return get_visual_script()->get_instance_base_type(); } else if (call_mode == CALL_MODE_NODE_PATH && get_visual_script().is_valid()) { Node *path = _get_base_node(); if (path) { return path->get_class(); } } return base_type; } int VisualScriptPropertyGet::get_input_value_port_count() const { return (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0; } int VisualScriptPropertyGet::get_output_value_port_count() const { int pc = (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 2 : 1; return pc; } String VisualScriptPropertyGet::get_output_sequence_port_text(int p_port) const { return String(); } PropertyInfo VisualScriptPropertyGet::get_input_value_port_info(int p_idx) const { if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) { if (p_idx == 0) { PropertyInfo pi; pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type); pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower()); return pi; } } return PropertyInfo(); } PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const { if (call_mode == CALL_MODE_BASIC_TYPE && p_idx == 0) { return PropertyInfo(basic_type, "pass"); } else if (call_mode == CALL_MODE_INSTANCE && p_idx == 0) { return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type()); } else { List<PropertyInfo> props; ClassDB::get_property_list(_get_base_type(), &props, false); for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { if (E->get().name == property) { PropertyInfo pinfo = PropertyInfo(E->get().type, String(property) + "." + String(index), E->get().hint, E->get().hint_string); _adjust_input_index(pinfo); return pinfo; } } } PropertyInfo pinfo = PropertyInfo(type_cache, "value"); _adjust_input_index(pinfo); return pinfo; } String VisualScriptPropertyGet::get_caption() const { String prop = property; if (index != StringName()) { prop += "." + String(index); } return vformat(RTR("Get %s"), prop); } String VisualScriptPropertyGet::get_text() const { if (call_mode == CALL_MODE_BASIC_TYPE) { return vformat(RTR("On %s"), Variant::get_type_name(basic_type)); } else if (call_mode == CALL_MODE_INSTANCE) { return vformat(RTR("On %s"), base_type); } else if (call_mode == CALL_MODE_NODE_PATH) { return " [" + String(base_path.simplified()) + "]"; } else { return RTR("On Self"); } } void VisualScriptPropertyGet::set_base_type(const StringName &p_type) { if (base_type == p_type) { return; } base_type = p_type; notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptPropertyGet::get_base_type() const { return base_type; } void VisualScriptPropertyGet::set_base_script(const String &p_path) { if (base_script == p_path) { return; } base_script = p_path; notify_property_list_changed(); ports_changed_notify(); } String VisualScriptPropertyGet::get_base_script() const { return base_script; } void VisualScriptPropertyGet::_update_cache() { if (call_mode == CALL_MODE_BASIC_TYPE) { // not super efficient.. Variant v; Callable::CallError ce; Variant::construct(basic_type, v, nullptr, 0, ce); List<PropertyInfo> pinfo; v.get_property_list(&pinfo); for (const PropertyInfo &E : pinfo) { if (E.name == property) { type_cache = E.type; return; } } } else { StringName type; Ref<Script> non_basic_script; Node *node = nullptr; if (call_mode == CALL_MODE_NODE_PATH) { node = _get_base_node(); if (node) { type = node->get_class(); base_type = type; // cache, too non_basic_script = node->get_script(); } } else if (call_mode == CALL_MODE_SELF) { if (get_visual_script().is_valid()) { type = get_visual_script()->get_instance_base_type(); base_type = type; // cache, too non_basic_script = get_visual_script(); } } else if (call_mode == CALL_MODE_INSTANCE) { type = base_type; if (!base_script.is_empty()) { if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) { ScriptServer::edit_request_func(base_script); // make sure it's loaded } if (ResourceCache::has(base_script)) { non_basic_script = ResourceCache::get_ref(base_script); } else { return; } } } bool valid = false; Variant::Type type_ret; type_ret = ClassDB::get_property_type(base_type, property, &valid); if (valid) { type_cache = type_ret; return; // all dandy } if (node) { Variant prop = node->get(property, &valid); if (valid) { type_cache = prop.get_type(); return; // all dandy again } } if (non_basic_script.is_valid()) { type_ret = non_basic_script->get_static_property_type(property, &valid); if (valid) { type_cache = type_ret; return; // all dandy } } } } void VisualScriptPropertyGet::set_property(const StringName &p_type) { if (property == p_type) { return; } property = p_type; _update_cache(); notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptPropertyGet::get_property() const { return property; } void VisualScriptPropertyGet::set_base_path(const NodePath &p_type) { if (base_path == p_type) { return; } base_path = p_type; notify_property_list_changed(); _update_base_type(); ports_changed_notify(); } NodePath VisualScriptPropertyGet::get_base_path() const { return base_path; } void VisualScriptPropertyGet::set_call_mode(CallMode p_mode) { if (call_mode == p_mode) { return; } call_mode = p_mode; notify_property_list_changed(); _update_base_type(); ports_changed_notify(); } VisualScriptPropertyGet::CallMode VisualScriptPropertyGet::get_call_mode() const { return call_mode; } void VisualScriptPropertyGet::set_basic_type(Variant::Type p_type) { if (basic_type == p_type) { return; } basic_type = p_type; notify_property_list_changed(); ports_changed_notify(); } Variant::Type VisualScriptPropertyGet::get_basic_type() const { return basic_type; } void VisualScriptPropertyGet::_set_type_cache(Variant::Type p_type) { type_cache = p_type; } Variant::Type VisualScriptPropertyGet::_get_type_cache() const { return type_cache; } void VisualScriptPropertyGet::_adjust_input_index(PropertyInfo &pinfo) const { if (index != StringName()) { Variant v; Callable::CallError ce; Variant::construct(pinfo.type, v, nullptr, 0, ce); Variant i = v.get(index); pinfo.type = i.get_type(); pinfo.name = String(property) + "." + index; } else { pinfo.name = String(property); } } void VisualScriptPropertyGet::set_index(const StringName &p_type) { if (index == p_type) { return; } index = p_type; _update_cache(); notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptPropertyGet::get_index() const { return index; } void VisualScriptPropertyGet::_validate_property( PropertyInfo &p_property) const { if (p_property.name == "base_type") { if (call_mode != CALL_MODE_INSTANCE) { p_property.usage = PROPERTY_USAGE_NO_EDITOR; } else { p_property.hint = PROPERTY_HINT_TYPE_STRING; p_property.hint_string = "Object"; } } if (p_property.name == "base_script") { if (call_mode != CALL_MODE_INSTANCE) { p_property.usage = PROPERTY_USAGE_NONE; } else { p_property.hint = PROPERTY_HINT_FILE; p_property.hint_string = "*.gd,*.cs,*.vs"; } } if (p_property.name == "basic_type") { if (call_mode != CALL_MODE_BASIC_TYPE) { p_property.usage = PROPERTY_USAGE_NONE; } else { p_property.hint = PROPERTY_HINT_ENUM; String hint_string; String enum_string = ""; for (int i = 0; i < Variant::VARIANT_MAX; i++) { Variant::Type type = static_cast<Variant::Type>(i); String type_name = Variant::get_type_name(type); if (i > 0) { enum_string += ","; } enum_string += type_name; } p_property.hint_string = enum_string; } } if (p_property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { p_property.usage = PROPERTY_USAGE_NONE; } else { p_property.hint = PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE; Node *bnode = _get_base_node(); if (bnode) { p_property.hint_string = bnode->get_path().simplified(); } } } if (p_property.name == "index") { Callable::CallError ce; Variant v; Variant::construct(type_cache, v, nullptr, 0, ce); List<PropertyInfo> plist; v.get_property_list(&plist); String options = ""; for (const PropertyInfo &E : plist) { options += "," + E.name; } p_property.hint = PROPERTY_HINT_ENUM; p_property.hint_string = options; p_property.type = Variant::STRING; if (options.is_empty()) { p_property.usage = PROPERTY_USAGE_NONE; // hide if type has no usable // index } } } void VisualScriptPropertyGet::_bind_methods() { ClassDB::bind_method(D_METHOD("set_base_type", "base_type"), &VisualScriptPropertyGet::set_base_type); ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptPropertyGet::get_base_type); ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptPropertyGet::set_base_script); ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptPropertyGet::get_base_script); ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptPropertyGet::set_basic_type); ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptPropertyGet::get_basic_type); ClassDB::bind_method(D_METHOD("_set_type_cache", "type_cache"), &VisualScriptPropertyGet::_set_type_cache); ClassDB::bind_method(D_METHOD("_get_type_cache"), &VisualScriptPropertyGet::_get_type_cache); ClassDB::bind_method(D_METHOD("set_property", "property"), &VisualScriptPropertyGet::set_property); ClassDB::bind_method(D_METHOD("get_property"), &VisualScriptPropertyGet::get_property); ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptPropertyGet::set_call_mode); ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptPropertyGet::get_call_mode); ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptPropertyGet::set_base_path); ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptPropertyGet::get_base_path); ClassDB::bind_method(D_METHOD("set_index", "index"), &VisualScriptPropertyGet::set_index); ClassDB::bind_method(D_METHOD("get_index"), &VisualScriptPropertyGet::get_index); String bt; for (int i = 0; i < Variant::VARIANT_MAX; i++) { if (i > 0) { bt += ","; } bt += Variant::get_type_name(Variant::Type(i)); } List<String> script_extensions; for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptServer::get_language(i)->get_recognized_extensions( &script_extensions); } String script_ext_hint; for (const String &E : script_extensions) { if (!script_ext_hint.is_empty()) { script_ext_hint += ","; } script_ext_hint += "." + E; } ADD_PROPERTY(PropertyInfo(Variant::INT, "set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script"); ADD_PROPERTY(PropertyInfo(Variant::INT, "type_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_type_cache", "_get_type_cache"); ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type"); ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "property"), "set_property", "get_property"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "index", PROPERTY_HINT_ENUM), "set_index", "get_index"); BIND_ENUM_CONSTANT(CALL_MODE_SELF); BIND_ENUM_CONSTANT(CALL_MODE_NODE_PATH); BIND_ENUM_CONSTANT(CALL_MODE_INSTANCE); BIND_ENUM_CONSTANT(CALL_MODE_BASIC_TYPE); } class VisualScriptNodeInstancePropertyGet : public VisualScriptNodeInstance { public: VisualScriptPropertyGet::CallMode call_mode; NodePath node_path; StringName property; StringName index; VisualScriptPropertyGet *node = nullptr; VisualScriptInstance *instance = nullptr; virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (call_mode) { case VisualScriptPropertyGet::CALL_MODE_SELF: { Object *object = instance->get_owner_ptr(); bool valid; *p_outputs[0] = object->get(property, &valid); if (index != StringName()) { *p_outputs[0] = p_outputs[0]->get_named(index, valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("Invalid index property name."); return 0; } } break; case VisualScriptPropertyGet::CALL_MODE_NODE_PATH: { Node *step_instance_call_mode_node = Object::cast_to<Node>(instance->get_owner_ptr()); if (!step_instance_call_mode_node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("Base object is not a Node!"); return 0; } Node *another = step_instance_call_mode_node->get_node(node_path); if (!another) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("Path does not lead Node!"); return 0; } bool valid; *p_outputs[0] = another->get(property, &valid); if (index != StringName()) { *p_outputs[0] = p_outputs[0]->get_named(index, valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = vformat(RTR("Invalid index property name '%s' in node %s."), String(property), another->get_name()); return 0; } } break; default: { bool valid; Variant v = *p_inputs[0]; *p_outputs[1] = v.get(property, &valid); if (index != StringName()) { *p_outputs[1] = p_outputs[1]->get_named(index, valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("Invalid index property name."); } *p_outputs[0] = v; }; } return 0; } }; VisualScriptNodeInstance * VisualScriptPropertyGet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstancePropertyGet *instance = memnew(VisualScriptNodeInstancePropertyGet); instance->node = this; instance->instance = p_instance; instance->property = property; instance->call_mode = call_mode; instance->node_path = base_path; instance->index = index; return instance; } VisualScriptPropertyGet::VisualScriptPropertyGet() { call_mode = CALL_MODE_SELF; base_type = "Object"; basic_type = Variant::NIL; type_cache = Variant::NIL; } template <VisualScriptPropertyGet::CallMode cmode> static Ref<VisualScriptNode> create_property_get_node(const String &p_name) { Ref<VisualScriptPropertyGet> node; node.instantiate(); node->set_call_mode(cmode); return node; } ////////////////////////////////////////// ////////////////EMIT////////////////////// ////////////////////////////////////////// int VisualScriptEmitSignal::get_output_sequence_port_count() const { return 1; } bool VisualScriptEmitSignal::has_input_sequence_port() const { return true; } int VisualScriptEmitSignal::get_input_value_port_count() const { Ref<VisualScript> vs = get_visual_script(); if (vs.is_valid()) { if (!vs->has_custom_signal(name)) { return 0; } return vs->custom_signal_get_argument_count(name); } return 0; } int VisualScriptEmitSignal::get_output_value_port_count() const { return 0; } String VisualScriptEmitSignal::get_output_sequence_port_text(int p_port) const { return String(); } PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const { Ref<VisualScript> vs = get_visual_script(); if (vs.is_valid()) { if (!vs->has_custom_signal(name)) { return PropertyInfo(); } return PropertyInfo(vs->custom_signal_get_argument_type(name, p_idx), vs->custom_signal_get_argument_name(name, p_idx)); } return PropertyInfo(); } PropertyInfo VisualScriptEmitSignal::get_output_value_port_info(int p_idx) const { return PropertyInfo(); } String VisualScriptEmitSignal::get_caption() const { return vformat(RTR("Emit %s"), name); } void VisualScriptEmitSignal::set_signal(const StringName &p_type) { if (name == p_type) { return; } name = p_type; notify_property_list_changed(); ports_changed_notify(); } StringName VisualScriptEmitSignal::get_signal() const { return name; } void VisualScriptEmitSignal::_validate_property( PropertyInfo &p_property) const { if (p_property.name == "signal") { p_property.hint = PROPERTY_HINT_ENUM; List<StringName> sigs; List<MethodInfo> base_sigs; Ref<VisualScript> vs = get_visual_script(); if (vs.is_valid()) { vs->get_custom_signal_list(&sigs); ClassDB::get_signal_list(vs->get_instance_base_type(), &base_sigs); } String ml; for (const StringName &E : sigs) { if (!ml.is_empty()) { ml += ","; } ml += E; } for (const MethodInfo &E : base_sigs) { if (!ml.is_empty()) { ml += ","; } ml += E.name; } p_property.hint_string = ml; } } void VisualScriptEmitSignal::_bind_methods() { ClassDB::bind_method(D_METHOD("set_signal", "name"), &VisualScriptEmitSignal::set_signal); ClassDB::bind_method(D_METHOD("get_signal"), &VisualScriptEmitSignal::get_signal); ADD_PROPERTY(PropertyInfo(Variant::STRING, "signal"), "set_signal", "get_signal"); } class VisualScriptNodeInstanceEmitSignal : public VisualScriptNodeInstance { public: VisualScriptEmitSignal *node = nullptr; VisualScriptInstance *instance = nullptr; int argcount = 0; StringName name; // virtual int get_working_memory_size() const override { return 0; } // virtual bool is_output_port_unsequenced(int p_idx) const { return false; } // virtual bool get_output_port_unsequenced(int p_idx,Variant* // r_value,Variant* p_working_mem,String &r_error) const { return true; } virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Object *obj = instance->get_owner_ptr(); obj->emit_signalp(name, p_inputs, argcount); return 0; } }; VisualScriptNodeInstance * VisualScriptEmitSignal::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceEmitSignal *instance = memnew(VisualScriptNodeInstanceEmitSignal); instance->node = this; instance->instance = p_instance; instance->name = name; instance->argcount = get_input_value_port_count(); return instance; } VisualScriptEmitSignal::VisualScriptEmitSignal() {} static Ref<VisualScriptNode> create_basic_type_call_node(const String &p_name) { Vector<String> path = p_name.split("/"); ERR_FAIL_COND_V(path.size() < 4, Ref<VisualScriptNode>()); String base_type = path[2]; String method = path[3]; Ref<VisualScriptFunctionCall> node; node.instantiate(); Variant::Type type = Variant::VARIANT_MAX; for (int i = 0; i < Variant::VARIANT_MAX; i++) { if (Variant::get_type_name(Variant::Type(i)) == base_type) { type = Variant::Type(i); break; } } ERR_FAIL_COND_V(type == Variant::VARIANT_MAX, Ref<VisualScriptNode>()); node->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE); node->set_basic_type(type); node->set_function(method); return node; } void register_visual_script_func_nodes() { VisualScriptLanguage::singleton->add_register_func( "functions/call", create_node_generic<VisualScriptFunctionCall>); VisualScriptLanguage::singleton->add_register_func( "functions/set", create_node_generic<VisualScriptPropertySet>); VisualScriptLanguage::singleton->add_register_func( "functions/get", create_node_generic<VisualScriptPropertyGet>); // VisualScriptLanguage::singleton->add_register_func("functions/call_script/call_self",create_script_call_node<VisualScriptScriptCall::CALL_MODE_SELF>); // VisualScriptLanguage::singleton->add_register_func("functions/call_script/call_node",create_script_call_node<VisualScriptScriptCall::CALL_MODE_NODE_PATH>); VisualScriptLanguage::singleton->add_register_func( "functions/emit_signal", create_node_generic<VisualScriptEmitSignal>); for (int i = 0; i < Variant::VARIANT_MAX; i++) { Variant::Type t = Variant::Type(i); String type_name = Variant::get_type_name(t); Callable::CallError ce; Variant vt; Variant::construct(t, vt, nullptr, 0, ce); List<MethodInfo> ml; vt.get_method_list(&ml); for (const MethodInfo &E : ml) { VisualScriptLanguage::singleton->add_register_func( "functions/by_type/" + type_name + "/" + E.name, create_basic_type_call_node); } } }
0
0.94917
1
0.94917
game-dev
MEDIA
0.396354
game-dev
0.962424
1
0.962424
AlessioDP/Parties
33,201
locales/bungeecord/messages_pt_PT.yml
--- #/ ===================================================== \ #| This is the BungeeCord messages file of Parties | #\ ===================================================== / #For any problem be sure to: #- Read the entire documentation on: https://alessiodp.com/docs/parties #- Join our Discord for further help: https://discord.alessiodp.com #/ =============================== \ #| PARTIES MESSAGES | #\ =============================== / parties: #[Special tags] #=> %version% = New version found #=> %thisversion% = Version installed update-available: "&9Nova versão de Parties foi encontrada: %version% (Atual: %thisversion%)" #[Special tags] #=> %config% = The configuration file name that is outdated configuration-outdated: "&cO ficheiro de configuração '%config%' de Parties está desatualizado!" common-messages: invalid-command: "&cComando incorreto" configuration-reloaded: "&aA foi configuração recarregada" not-in-party: "&cNão está em uma party" already-in-party: "&cJá está em uma party!" party-not-found: "&cEssa party %party% não existe" party-full: "&cEssa party está cheia!" player-not-found: "&cO jogador %player% não foi detectado" player-not-in-party: "&c%player% não está em uma party" options: enabled: '&aAtivado' disabled: '&cDesativado' toggled-on: '&aAtivado' toggled-off: '&cDesativo' word-yes: '&a Sim' word-no: '&c Não' empty: '&8Vazia' none: '&8Nenhum' syntax: wrong-message: '&cSintaxe incorreta: Escreva &7/%syntax%' color: 'coloração' description: 'detalhes' experience: 'experience' kills: 'matanças' home: 'lar' members: 'jogadores' message: 'mensagem' motd: 'motd' name: 'nome' nickname: 'nome' online-members: 'membros ativos' order: 'ordem' page: 'página' party: 'party' password: 'palavra-passe' permission: 'permissão' player: 'jogador' rank: 'grupo' tag: 'tag' permissions: #[Special tags] #=> %permission% = Missing permission no-permission: "&cNão tem permissão para executar este comando" no-permission-in-party-general: "&cO seu grupo na party não tem permissão para executar este comando" no-permission-in-party-rank: "&cPrecisa ser %rank_name% para executar esse comando" out-party: "Fora da party" list: player-online-format: "&b%player%" player-offline-format: "&7%player%" player-separator: "&7, " player-empty: "&7Ninguém" player-unknown: "&6Alguém" missing-value: "&7Perdida" #Define the format of Parties chat messages formats: party-chat: "&b[Party] %player_rank_chat% %player%&r&7: &b%message%" spy: party-chat: "&7[ESPIA] [%party%] %player%: %message%" broadcast: "&7[ESPIA] [%party%] %message%" #/ =============================== \ #| MAIN COMMANDS MESSAGES | #\ =============================== / main-commands: accept: no-request: "&cNão tem nenhum pedido pendente" no-exists: "&cO pedido deixou de existir" multiple-requests: "&cSeleccione o pedido que pretende aceitar:" multiple-requests-party: '[{"text":"%party%","color":"aqua"},{"text":" - Clique para aceitar","color":"gray","clickEvent":{"action":"run_command","value":"/%run_command% %party%"},"hoverEvent":{"show_text","value":{"text":"","extra":{"text":"text":"Aceitar pedido","color":"gold"}]}}}]' multiple-requests-player: '[{"text":"%player%","color":"aqua"},{"text":" - Clique aqui para aceitar","color":"gray","clickEvent":{"action":"run_command","value":"/%run_command% %player%"},"hoverEvent":{"show_text","value":{"text":"","extra":{"text":"text":"Aceitar o pedido","color":"gold"}]}}}]' chat: enabled: "&aChat foi definido para party" disabled: "&aChat alternardo para público" create: created: "[{\"text\":\"Criou a party %party%.\n\",\"color\":aqua\",\"bold\":true},{\"text\":\"Type \",\"color\":\"aqua\",\"bold\":false},{\"text\":\"/party invite\",\"color\":\"gray\",\"clickEvent\":{\"action\":{\"suggest_command\",\"value\":\"/party invite \"}},{\"text\":\" para convidar um amigo.\",\"color\":\"aqua\"}]" created-fixed: "&b&lCriou uma party fixa %party%" name-already-exists: "&cO nome da party %party% já existe, escolha um nome de party diferente" name-too-long: "&cO nome da party é muito comprido!" name-too-short: "&cO nome da party é demasiado pequeno!" invalid-name: "&cCaracteres não válidos. Utilizar: a-Z ou 0-9." censored: "&cO nome do party contém palavras censuradas!" delete: deleted: "&aParty %party% foi eliminada" deleted-silently: "&aParty %party% apagada silenciosamente" broadcast: "&6&lA sua party foi apagada" deny: no-request: "&cNão tem nenhum pedido pendente" no-exists: "&cO pedido deixou de existir" multiple-requests: "&cSeleccione o pedido que pretende recusar:" multiple-requests-party: '[{"text":"%party%","color":"aqua"},{"text":" - Clique para aceitar","color":"gray","clickEvent":{"action":"run_command","value":"/%run_command% %party%"},"hoverEvent":{"show_text","value":{"text":"","extra":{"text":"text":"Aceitar pedido","color":"gold"}]}}}]' multiple-requests-player: '[{"text":"%player%","color":"aqua"},{"text":" - Clique para aceitar","color":"gray","clickEvent":{"action":"run_command","value":"/%run_command% %player%"},"hoverEvent":{"show_text","value":{"text":"","extra":{"text":"text":"Aceitar pedido","color":"gold"}]}}}]' ignore: start-ignore: "&7A ignorar %party% convites" stop-ignore: "&7Paraste de ignorar %party%" ignore-list: header: "&b&lListagem de parties ignoradas:" party-prefix: "&c" separator: "&7, " empty: "&7Nenhum" info: content-own-party: - "&b============ &lInformações para %party%&r&b============" - "&b&l&Descrição para &7: %desc%" - "&bLíder &7: %list_rank_leader%" - "&bMods&7: %list_rank_moderator%" - "&bOs membros&7: %list_rank_member%" - "&bJogadores online&7: %members_online_total%" content-other-party: - "&b============ &lInformações para %party%&r&b============" - "&b&l&Descrição para &7: %desc%" - "&bLíder &7: %list_rank_leader%" - "&bMods&7: %list_rank_moderator%" - "&bOs membros&7: %list_rank_member%" - "&bJogadores online&7: %members_online_total%" invite: sent: "&bConvidaste %player% para a sua party" player-invited: "[{\"text\":\"&b%player% convidou-o para a sua party %party%.\n&bVocê quer \"},{\"text\":\"&a&laceito\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/party accept %party%\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"&6Aceitar convite\"}]}}}, \"text\":\" &bou \"},{\"text\":\"&c&ldeny\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/party deny %party%\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"&6Recusar convite\"}]}}},{\"text\":\"&b?\n&bPode usar &7/party <accept/deny> &bpara escolher.\"}]" accept: broadcast: "&b&l%player% entrou na party" accepted: "&aAceitaste o convite da party" receipt: "&a%player% aceitou o teu convite" deny: broadcast: "" denied: "&aNegou o convite da party" receipt: "&a%player% negou o teu convite" timeout: no-response: "&7%player% não aceitou o convite par a party" timeout: "&7Não aceitou o convite da party para %party%" revoke: sent-revoked: "&7Convite anulado enviado para %player%" player-invite-revoked: "&7Convite recebido de %party% foi anulado" cooldown: global: "&cPrecisas esperar %seconds% segundos antes de convidar outro jogador" individual: "&cPrecisas esperar %seconds% segundos antes de convidar outro jogador" on-leave: "&cPrecisas esperar %seconds% segundos antes de convidar outro jogador" player-offline: "&cSó podes convidar jogadores ativos" player-no-permission: "&c%player% não tens permissão para entrar" player-in-party: "&c%player% já estás numa party" already-invited: "&c%player% já tinha sido convidado" invite-yourself: "&cNão podes convidar ti mesmo" failed: "&cErro ao convidar o jogador %player%" kick: sent: "&aExpulsou %player% da party!" player-kicked: "&bFoi expulso da %party%" broadcast: "&b&l%player% foi expulso da party" broadcast-disband: "&b&lA party foi desfeita porque o líder foi expulso" broadcast-leader-changed: "&b&lO novo líder é %player%" broadcast-leave-server: "&b&l%player% foi expulso da party" player-higher-rank: "&cNão pode expulsar o seu superior!" player-not-in-party: "&c%player% não está na sua party" players-conflict: #[Special tags] #=> %username% = The name of the player #=> %rank% = The rank #=> %list_players% = List of each player #=> %number% = The number of the player #=> %lastloginapi_last_logout_date% = The last logout date (See LastLoginAPI plugin) content: - "&cEncontrámos alguns jogadores com esse nome:" - "%list_players%" - "&cUse '&7/party kick <username> <number>&c para expulsar o jogador certo" player: '{"text":"","extra":[{"text":"[%number%] ","color":"gray"},{"text":"%username%","color":"gold"},{"text":" [","color":"gray"},{"text":"%party%","color":"aqua"},{"text":"]: Última entrada %lastloginapi_last_logout_date%","color":"gray"}],"clickEvent":{"action":"run_command","value":"/party kick %username% %number%"},"hoverEvent":{"action":"show_text","value":{"text":"Expulsar este jogador","color":"gold"}}}' leave: left: "&b&lSaiu da party %party%" broadcast: "&b&l%player% saiu da party" party-disbanded: "&6&lA party foi desfeita porque o líder saiu" leader-changed: "&b&lO líder saiu da party, o novo líder é %player%" p: #[Special tags] #=> %seconds% = Remaining time in seconds cooldown: "&cTem ainda que aguardar %seconds% segundos" censored: "&cA mensagem contém palavras censuradas!" muted: "&cEstá silenciado!" rank: #[Special tags] #=> %rank_name% = Rank wrote by the player changed: "O rank de &a%player% foi alterado para %rank_name%" broadcast: "" wrong-rank: "&cO grupo '%rank_name%' não existe!" same-rank: "&c%player% ja é %rank_name%!" low-rank: "&cNão pode editar jogadores com um grupo equivalente ou superior ao seu!" to-higher-rank: "&cNão pode promover jogadores com um grupo equivalente ou superior ao seu!" full: "&cO grupo %rank_name% alcançou o número máximo de jogadores" fixed-leader: "&cNão pode fazer de alguém um líder de uma party fixa!" demote-leader: "&cNão pode despromover o líder da party" changing-yourself: "&cNão pode alterar o seu próprio grupo!" player-not-in-party: "&c%player% não está na sua party" players-conflict: #[Special tags] #=> %username% = The name of the player #=> %rank% = The rank #=> %list_players% = List of each player #=> %number% = The number of the player #=> %lastloginapi_last_logout_date% = The last logout date (See LastLoginAPI plugin) content: - "&cEncontrámos alguns jogadores com esse nome:" - "%list_players%" - "&cUse '&7/party rank <username> <rank> <number>&c' para mudar o grupo do jogador certo" player: '{"text":"","extra":[{"text":"[%number%] ","color":"gray"},{"text":"%username%","color":"gold"},{"text":" [","color":"gray"},{"text":"%party%","color":"aqua"},{"text":"]: Última entrada %lastloginapi_last_logout_date%","color":"gray"}],"clickEvent":{"action":"run_command","value":"/party rank %username% %rank% %number%"},"hoverEvent":{"action":"show_text","value":{"text":"Altera o grupo do jogador","color":"gold"}}}' rename: #[Special tags] #=> %old% = Old party name renamed: "&aA party %old% foi renomeada para %party%" broadcast: "&6A sua party foi renomeada para %party%!" #[Special tags] #=> %seconds% = Remaining time in seconds cooldown: "&cTem de esperar %seconds% segundos!" spy: enabled: "&7É agora um espião!" disabled: "&7Já não é um espião" version: #[Special tags] #=> %version% = Parties version #=> %newversion% = Latest Parties version #=> %platform% = Platform of the plugin (e.g. Bukkit, BungeeCord) updated: "&b&lParties &b%version% &7(%platform%) - Desenvolvido por &6AlessioDP" outdated: "&b&lParties &b%version% &7(%platform%) - Desenvolvido por &6AlessioDP\n&aNova versão encontrada: &2%newversion%" #/ =============================== \ #| ADDITIONAL COMMANDS MESSAGES | #\ =============================== / additional-commands: ask: sent: "&aPedido de entrada enviado por %party%" received: "[{\"text\":\"&b%player% deseja entrar na sua party.\n&bDeseja \"},{\"text\":\"&a&laceitar\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/party accept %player%\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"&6Aceitar o pedido\"}]}}},{\"text\":\" &bor \"},{\"text\":\"&c&ldeny\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/party deny %player%\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Recusar o convite\",\"color\":\"gold\"}]}}},{\"text\":\"&b?\n&bPode &7/party <accept/deny> %player% &bpara escolher.\"}]" accept: broadcast: "&b&l%player% entrou na party" accepted: "&aAceitou o pedido" receipt: "&a%party% aceitou o seu pedido" deny: broadcast: "" denied: "&aRecusou o pedido de %player%" receipt: "&a%party% recusou seu pedido" timeout: no-response: "&7%party% não aceitou o seu pedido" cooldown: #[Special tags] #=> %seconds% = Remaining time in seconds global: "&cPrecisa aguardar %seconds% segundos antes de falar noutra party" individual: "&cPrecisa de aguardar %seconds% segundos antes de perguntar na mesma party" color: info: "&bA cor da sua party é: %color_code%%color_command%" empty: "&bA sua party não tem uma cor" changed: "&bA cor da party foi alterada para %color_command%" removed: "&bCor da party removida" broadcast: "" #Syntax of %available_colors% available-colors: color: "%color_command%" separator: ", " wrong-color: "&cCor não encontrada. Seleccione: %available_colors%" debug: bungeecord: sync: "Parties in the server %server% is synced correctly" not-sync: "Parties in the server %server% is NOT synced correctly" config: header: '&b================== &lDebug Config &r&b==================' text: - "&bOutdated config/parties/messages:&7 %outdated_config%&7/%outdated_parties%&7/%outdated_messages%" - "&bStorage&7: %storage%" - "&bRanks&7: %ranks%" rank-format: '&f%name%&7[%level%]' rank-separator: '&7, ' exp: header: '&b=================== &lDebug Exp &r&b===================' text: - "&bExp system&7: %exp%" - "&bEarn from mobs: %earn%" - "&bMode&7: %mode%" - "%mode_options%" mode-options: progressive: "&bProgressive start&7: %start%\n&bFormula&7: '%formula%'" fixed: "&bFixed repeat&7: %repeat%&bLevels&7: %levels%" party: header: '&b================== &lDebug Party &r&b==================' text: - "&bID&7: %id%" - "&bName/tag&7: %name%&7/%tag%" - "&bLeader&7: %leader%" - "&bNumber members/online&7: %members%&7/%members_online%" - "&bDescription&7: %description%" - "&bMOTD size/homes/kills&7: %motd_size%&7/%homes%&7/%kills%" - "&bPassword/protection/follow/open&7: %password%&7/%protection%&7/%follow%&7/%open%" - "&bColor set/active/dynamic&7: %color%&7/%color_active%&7/%color_dynamic%" - "&bExperience&7: %experience%" player: header: '&b================== &lDebug Player &r&b==================' text: - "&bUUID&7: %uuid%" - "&bName&7: %name%" - "&bRank&7: %rank%" - "&bParty&7: %party%" - "&bChat/spy/muted&7: %chat%&7/%spy%&7/%muted%" - "&bProtection bypass&7: %protection_bypass%" player-offline: "&cThe player '%player%' must be online" desc: changed: "&bDescrição da party alterada" removed: "&bDescrição da party removida" broadcast: "" invalid-chars: "&cCaracteres inválidos. Utilize: a-Z ou 0-9. Mínimo 3 e máximo 16 caracteres." censored: "&cA descrição contém palavras censuradas!" exp: #[Special tag] #=> %exp% = Experience gained gained-experience: "&bGanhou %exp% experiência de party por matar o mob" level-up: "&bA party subiu de nível para %experience_level%" follow: toggle-on: "&aAgora os membros da sua party seguirão o seu líder" toggle-off: "&aOs membros da sua party já não seguem o seu líder" home: teleported: "&7Teletransportado para a casa da party" #[Special tags] #=> %seconds% = Time of delay in seconds teleport-in: "&7Será teletransportado em %seconds% segundos..." teleport-cancelled: "&7Teletransporte cancelado" teleport-waiting: "&cJá está à espera do teletransporte!" no-home: "&cAinda não existe uma casa definida" #[Special tags] #=> %seconds% = Remaining time in seconds cooldown: "&cTem de esperar %seconds% segundos!" must-select-home: "&cDeve selecionar uma casa válida" invalid-home: "&cA casa selecionada não existe" valid-homes: "&bLista de casas válidas:" #[Special tags] #Any value related to home: %name%, %world%, %server%, %x%, %y%, %z%, %pitch% & %yaw% valid-home-line: '[{"text":"&b%name%","clickEvent":{"action":"run_command","value":"/party home %name%"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"&aClicar para teletransportar"}]}}}]' join: joined: "&aJuntou-se à party %party%" player-joined: "&b&l%player% juntou-se à party" open-close: opened: "&bA party está agora aberta" closed: "&bA party está agora fechada" already-open: "&cA party já se encontra aberta" already-closed: "&cA party já se encontra fechada" cooldown: "&cTem de esperar %seconds% segundos!" cannot-join: "&cNão pode juntar-se a esta party" failed: "&cFalha ao abrir a party" password: wrong-password: "&cPalavra-passe errada!" list: #[Special tags] #=> %index% = The party index #=> %number% = Number of online parties #=> %page% = Current page of the list #=> %maxpages% = Total pages header: "&b============ &lLista de parties online &r&b============" footer: "&b================ &lPágina %page% de %maxpages% &r&b================" no-one: "&7Ninguém" format-party: '[{"text":"&b%party%","clickEvent":{"action":"run_command","value":"/party info %party%"},"hoverEvent":{"action":"show_text","value":{"text":"","extra":[{"text":"&aMostrar info"}]}}},{"text":" &7[&6Online %members_online_total%&7] %desc%"}]' invalid-order: '&cTipo de ordem inválida' motd: changed: "&bA MOTD da party mudou" removed: "&bMOTD da party removida" broadcast: "" content: - "&bMOTD da party:" - "&b%motd%" invalid-chars: "&cCaracteres inválidos. Poderá também usar '. , /'. Mínimo 3 e máximo 100 caracteres." censored: "&cA MOTD contém palavras censuradas!" mute: toggle-on: "&7Desativou as notificações!" toggle-off: "&7Ativou as notificações!" nickname: own: changed: "&bMudou o seu nickname para %player_nickname%" removed: "&bRemoveu o seu próprio nickname" no-permission: "&cNão pode alterar o seu próprio nickname" others: changed: "&bAlterou a alcunha de %player% para %player_nickname%" #Special tags: #=> %nickname% = The target player nickname #Tags are parsed for sender target-changed: "&b%player% mudou o seu nickname para %nickname%" removed: "&bRemoveu o nickname de %player%" target-removed: "&b%player% removeu o seu nickname" no-permission: "&cNão pode alterar os nicknames de outros jogadores" show: own: "&bO seu nickname é %player_nickname%" own-none: "&bNão tem nickname" other: "&bO nickname de %player% é %player_nickname%" other-none: "&b%player% não tem um nickname" invalid-chars: "&cCaracteres inválidos. Também pode utilizar '. , /'. Mínimo 3 e máximo 16 caracteres." censored: "&cO nickname contém palavras censuradas!" password: changed: "&aPalavra-passe da party alterada" removed: "&aPalavra-passe da party removida" broadcast: "" invalid-chars: "&cCaracteres inválidos. Utilizar: a-Z ou 0-9. Mínimo 1 e máximo 16 caracteres." protection: toggle-on: "&aAgora a sua party está protegido por fogo amigo" toggle-off: "&aA sua party já não está protegida por fogo amigo" protected: "&cNão pode atingir os seus membros de party" warn-on-attack: "&c%player% tentou atingir %victim%!" sethome: changed: "" removed: "&bCasa da party removida" removed-none: "&cNão foi encontrada nenhuma casa nesta party" broadcast: "&aA party tem uma nova casa!" #[Special tags] #=> %seconds% = Remaining time in seconds cooldown: "&cTem de esperar %seconds% segundos!" max-homes: "&cAtingiu o número máximo de casas" tag: changed: "&bAlteração da tag da party" removed: "&bTag da party removida" broadcast: "" invalid-chars: "&cCaracteres inválidos. Utilizar: a-Z ou 0-9. Mínimo 3 e máximo 10 caracteres." censored: "&cA tag contém palavras censuradas!" already-used: "&c A tag %tag% já está a ser usada" teleport: teleporting: "&7A teletransportar a sua party para aqui!" player-teleported: "&bTeletransportado para %player%" #[Special tags] #=> %seconds% = Time of delay in seconds player-teleport-in: "&7Será teletransportado em %seconds% segundos" player-teleport-cancelled: "&7Teletransporte cancelado" #[Special tags] #=> %seconds% = Remaining time in seconds cooldown: "&cTem de esperar %seconds% segundos!" accept-request: sent: "&aPedido de teletransporte enviado para a party" received: "[{\"text\":\"&bQuer ser teletransportado para %player%? \"},{\"text\":\"&a&lYes\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/party accept %player%\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"&6Aceitar o pedido\"}]}}},{\"text\":\" &bou\"},{\"text\":\"&c&lnão\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/party deny %player%\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"Deny the invitation\",\"color\":\"gold\"}]}}},{\"text\":\"&b?\n&bPode usar &7/party <accept/deny> %player% &bpara escolher.\"}]" denied: "&7Negou o pedido de teletransporte de %player%" #/ =============================== \ #| OTHER MESSAGES | #\ =============================== / other: follow: #[Special tags] #=> %server% = New server following-server: "&7Seguindo %player% em %server%" fixed-parties: default-join: "&bEntrou na %party%" join-leave: server-join: "&b%player% está online!" server-leave: "&7%player% está offline!" #/ =============================== \ #| HELP MESSAGES | #\ =============================== / help: header: "&b================= &lAjuda %page%/%maxpages% &r&b=================" footer: "" perform-command: 'Executar o comando' console-help: header: 'Só é possível executar estes comandos:' command: ' > %command% - %description%' #[Special tags] #=> %syntax% = Command syntax #=> %description% = Description #=> %run_command% = Command run syntax #=> %perform_command% = Perform command message main: commands: help: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' accept: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' chat: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' create: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' delete: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' deny: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' ignore: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' info: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' invite: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' kick: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' leave: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' p: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' rank: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' reload: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' rename: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' spy: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' version: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' descriptions: help: 'Mostrar páginas de ajuda' accept: 'Aceitar um pedido de party' chat: 'Alternar mensagens da party' create: 'Criar uma nova party' delete: 'Apagar a party' deny: 'Recusar um pedido de party' ignore: 'Adicionar/remover/mostrar parties ignoradas' info: 'Mostrar informações da party' invite: 'Convidar um jogador para a party' kick: 'Expulsar um jogador da party' leave: 'Sair da party' p: 'Enviar uma mensagem para a party' rank: 'Alterar o grupo do jogador' reload: 'Recarregar ficheiros de configuração das parties' rename: 'Renomear a party' spy: 'Espiar mensagens de outras parties' version: 'Mostrar informações de parties' additional: commands: ask: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' claim: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' close: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' color: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' createfixed: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' debug: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' desc: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' follow: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' home: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' join: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' list: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' motd: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' mute: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' nickname: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' open: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' password: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' protection: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' sethome: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' tag: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"suggest_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' teleport: '{"text":"&b/%syntax% &7- %description%","clickEvent":{"action":"run_command","value":"/%run_command% "},"hoverEvent":{"action":"show_text","value":{"text":"&6%perform_command%"}}}' descriptions: ask: 'Enviar um pedido de adesão' claim: 'Conceder permissões à reivindicação' close: 'Encerrar a party' color: 'Alterar a cor da party' createfixed: 'Criar uma nova party fixa' debug: 'Debug issues' desc: 'Definir/remover a descrição da party' follow: 'Alternar seguir o líder' home: 'Teletransportar para a casa da party' join: 'Entrar na party' list: 'Lista de parties online' motd: 'Definir/remover o motd da party' mute: 'Alternar notificações' nickname: 'Definir/remover nickname de um membro' open: 'Abrir a party' password: 'Alterar a palavra-passe da party' protection: 'Proteção contra fogo amigo' sethome: 'Definir/remover a casa da party' tag: 'Definir/remover tag da party' teleport: 'Teletransportar a sua party para si' dont-edit-this: version: 14
0
0.893279
1
0.893279
game-dev
MEDIA
0.838846
game-dev
0.528824
1
0.528824
Snaiel/Godot4ThirdPersonCombatPrototype
2,962
scripts/camera_controller/dizzy_finisher/camera_controller_dizzy_finisher_from_damage_state.gd
class_name CameraControllerDizzyFinisherFromDamageState extends CameraControllerStateMachine @export var normal_state: CameraControllerNormalState # used for if victim was killed var _recently_killed_dizzy_victim: bool = false var _transition_out: bool = false # 1 offsets the camera right # -1 offset the camera left var _cam_right_or_left: int = 1 @onready var dizzy_system: DizzySystem = Globals.dizzy_system func enter() -> void: var diff_in_rotation: float = wrapf( camera_controller.rotation_degrees.y - player.rotation_degrees.y, 0.0, 360.0 ) if 182 < diff_in_rotation and diff_in_rotation < 345: _cam_right_or_left = -1 else: _cam_right_or_left = 1 func process_camera() -> void: var dizzy_victim: DizzyComponent = dizzy_system.dizzy_victim if not dizzy_victim: _recently_killed_dizzy_victim = true if _recently_killed_dizzy_victim: _recently_killed_dizzy_victim = false var timer: SceneTreeTimer = get_tree().create_timer(0.7) timer.timeout.connect( func(): _transition_out = true ) # prints(dizzy_victim, _recently_killed_dizzy_victim) if dizzy_victim: camera.fov = move_toward( camera.fov, 65, 2 ) camera_controller.global_position = camera_controller.global_position.lerp( player.global_position + Vector3(0, 0.5, 0), 0.05 ) camera.look_at(dizzy_victim.global_position) camera.global_rotation_degrees.y += _cam_right_or_left * 20 camera_controller.rotation_degrees.x = lerp_angle( camera_controller.rotation_degrees.x, -35.0, 0.05 ) var _looking_direction: Vector3 = camera_controller\ .global_position\ .direction_to(dizzy_victim.global_position) _looking_direction = -_looking_direction var _target_look: float = atan2( _looking_direction.x, _looking_direction.z ) _target_look += _cam_right_or_left * deg_to_rad(80) var desired_rotation_y: float = lerp_angle( camera_controller.rotation.y, _target_look, 0.1 ) camera_controller.rotation.y = desired_rotation_y elif _transition_out: if player.input_direction.length() > 0 or \ lock_on_system.target != null: return_back_to_normal_cam() return camera.fov = move_toward( camera.fov, camera_controller.camera_fov, 2 ) camera_controller.global_position = camera_controller\ .global_position\ .lerp( player.global_position + Vector3( 0, camera_controller.vertical_offset, 0 ), 0.1 ) camera.rotation = camera.rotation.lerp(Vector3.ZERO, 0.1) camera_controller.rotation.y = lerp_angle( camera_controller.rotation.y, player.rotation.y, 0.1 ) if abs( camera_controller.rotation.y \ - player.rotation.y ) < 0.05: return_back_to_normal_cam() return func return_back_to_normal_cam() -> void: print("Return back to normal cam after dizzy finisher from damage camera behaviour") parent_state.parent_state.change_state( normal_state )
0
0.97959
1
0.97959
game-dev
MEDIA
0.952394
game-dev
0.976157
1
0.976157
The-Cataclysm-Preservation-Project/TrinityCore
11,470
src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Instance_Mount_Hyjal SD%Complete: 100 SDComment: Instance Data Scripts and functions to acquire mobs and set encounter status for use in various Hyjal Scripts SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" #include "GameObject.h" #include "GameObjectAI.h" #include "hyjal.h" #include "InstanceScript.h" #include "Log.h" #include "Map.h" #include "Player.h" #include "ScriptedCreature.h" #include "WorldPacket.h" #include "WorldSession.h" /* Battle of Mount Hyjal encounters: 0 - Rage Winterchill event 1 - Anetheron event 2 - Kaz'rogal event 3 - Azgalor event 4 - Archimonde event */ namespace BattleForMountHyjal { enum Yells { YELL_ARCHIMONDE_INTRO = 8 }; ObjectData const creatureData[] = { { NPC_CHANNEL_TARGET, DATA_CHANNEL_TARGET }, { 0, 0 } // END }; class instance_hyjal : public InstanceMapScript { public: instance_hyjal() : InstanceMapScript(HyjalScriptName, 534) { } struct instance_mount_hyjal_InstanceMapScript : public InstanceScript { instance_mount_hyjal_InstanceMapScript(InstanceMap* map) : InstanceScript(map) { SetHeaders(DataHeader); LoadObjectData(creatureData, nullptr); memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); RaidDamage = 0; Trash = 0; hordeRetreat = 0; allianceRetreat = 0; ArchiYell = false; } bool IsEncounterInProgress() const override { for (uint8 i = 0; i < EncounterCount; ++i) if (m_auiEncounter[i] == IN_PROGRESS) return true; return false; } void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { case GO_HORDE_ENCAMPMENT_PORTAL: HordeGate = go->GetGUID(); if (allianceRetreat) HandleGameObject(ObjectGuid::Empty, true, go); else HandleGameObject(ObjectGuid::Empty, false, go); break; case GO_NIGHT_ELF_VILLAGE_PORTAL: ElfGate = go->GetGUID(); if (hordeRetreat) HandleGameObject(ObjectGuid::Empty, true, go); else HandleGameObject(ObjectGuid::Empty, false, go); break; case GO_ANCIENT_GEM: m_uiAncientGemGUID.push_back(go->GetGUID()); break; } } void OnCreatureCreate(Creature* creature) override { switch (creature->GetEntry()) { case RAGE_WINTERCHILL: RageWinterchill = creature->GetGUID(); break; case ANETHERON: Anetheron = creature->GetGUID(); break; case KAZROGAL: Kazrogal = creature->GetGUID(); break; case AZGALOR: Azgalor = creature->GetGUID(); break; case ARCHIMONDE: Archimonde = creature->GetGUID(); if (GetData(DATA_AZGALOREVENT) != DONE) creature->SetVisible(false); break; case JAINA: JainaProudmoore = creature->GetGUID(); break; case THRALL: Thrall = creature->GetGUID(); break; case TYRANDE: TyrandeWhisperwind = creature->GetGUID(); break; } InstanceScript::OnCreatureCreate(creature); } ObjectGuid GetGuidData(uint32 identifier) const override { switch (identifier) { case DATA_RAGEWINTERCHILL: return RageWinterchill; case DATA_ANETHERON: return Anetheron; case DATA_KAZROGAL: return Kazrogal; case DATA_AZGALOR: return Azgalor; case DATA_ARCHIMONDE: return Archimonde; case DATA_JAINAPROUDMOORE: return JainaProudmoore; case DATA_THRALL: return Thrall; case DATA_TYRANDEWHISPERWIND: return TyrandeWhisperwind; } return ObjectGuid::Empty; } void SetData(uint32 type, uint32 data) override { switch (type) { case DATA_RAGEWINTERCHILLEVENT: m_auiEncounter[0] = data; break; case DATA_ANETHERONEVENT: m_auiEncounter[1] = data; break; case DATA_KAZROGALEVENT: m_auiEncounter[2] = data; break; case DATA_AZGALOREVENT: m_auiEncounter[3] = data; if (data == DONE) { instance->LoadGrid(5581.49f, -3445.63f); if (Creature* archimonde = instance->GetCreature(Archimonde)) { archimonde->SetVisible(true); if (!ArchiYell) { ArchiYell = true; archimonde->AI()->Talk(YELL_ARCHIMONDE_INTRO); } } } break; case DATA_ARCHIMONDEEVENT: m_auiEncounter[4] = data; break; case DATA_RESET_TRASH_COUNT: Trash = 0; break; case DATA_TRASH: if (data) Trash = data; else Trash--; DoUpdateWorldState(WORLD_STATE_ENEMYCOUNT, Trash); break; case TYPE_RETREAT: if (data == SPECIAL) { if (!m_uiAncientGemGUID.empty()) { for (GuidList::const_iterator itr = m_uiAncientGemGUID.begin(); itr != m_uiAncientGemGUID.end(); ++itr) { //don't know how long it expected DoRespawnGameObject(*itr, DAY); } } } break; case DATA_ALLIANCE_RETREAT: allianceRetreat = data; HandleGameObject(HordeGate, true); SaveToDB(); break; case DATA_HORDE_RETREAT: hordeRetreat = data; HandleGameObject(ElfGate, true); SaveToDB(); break; case DATA_RAIDDAMAGE: RaidDamage += data; if (RaidDamage >= MINRAIDDAMAGE) RaidDamage = MINRAIDDAMAGE; break; case DATA_RESET_RAIDDAMAGE: RaidDamage = 0; break; } TC_LOG_DEBUG("scripts", "Instance Hyjal: Instance data updated for event %u (Data=%u)", type, data); if (data == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << ' ' << m_auiEncounter[1] << ' ' << m_auiEncounter[2] << ' ' << m_auiEncounter[3] << ' ' << m_auiEncounter[4] << ' ' << allianceRetreat << ' ' << hordeRetreat << ' ' << RaidDamage; str_data = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } uint32 GetData(uint32 type) const override { switch (type) { case DATA_RAGEWINTERCHILLEVENT: return m_auiEncounter[0]; case DATA_ANETHERONEVENT: return m_auiEncounter[1]; case DATA_KAZROGALEVENT: return m_auiEncounter[2]; case DATA_AZGALOREVENT: return m_auiEncounter[3]; case DATA_ARCHIMONDEEVENT: return m_auiEncounter[4]; case DATA_TRASH: return Trash; case DATA_ALLIANCE_RETREAT: return allianceRetreat; case DATA_HORDE_RETREAT: return hordeRetreat; case DATA_RAIDDAMAGE: return RaidDamage; } return 0; } std::string GetSaveData() override { return str_data; } void Load(char const* in) override { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); std::istringstream loadStream(in); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4] >> allianceRetreat >> hordeRetreat >> RaidDamage; for (uint8 i = 0; i < EncounterCount; ++i) if (m_auiEncounter[i] == IN_PROGRESS) // Do not load an encounter as IN_PROGRESS - reset it instead. m_auiEncounter[i] = NOT_STARTED; OUT_LOAD_INST_DATA_COMPLETE; } protected: uint32 m_auiEncounter[EncounterCount]; std::string str_data; GuidList m_uiAncientGemGUID; ObjectGuid RageWinterchill; ObjectGuid Anetheron; ObjectGuid Kazrogal; ObjectGuid Azgalor; ObjectGuid Archimonde; ObjectGuid JainaProudmoore; ObjectGuid Thrall; ObjectGuid TyrandeWhisperwind; ObjectGuid HordeGate; ObjectGuid ElfGate; uint32 Trash; uint32 hordeRetreat; uint32 allianceRetreat; uint32 RaidDamage; bool ArchiYell; }; InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_mount_hyjal_InstanceMapScript(map); } }; } void AddSC_instance_mount_hyjal() { using namespace BattleForMountHyjal; new instance_hyjal(); }
0
0.988088
1
0.988088
game-dev
MEDIA
0.91225
game-dev
0.994449
1
0.994449
RecursivePineapple/MatterManipulator
5,692
src/main/java/com/recursive_pineapple/matter_manipulator/common/entities/EntityItemLarge.java
package com.recursive_pineapple.matter_manipulator.common.entities; import java.util.Iterator; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import com.recursive_pineapple.matter_manipulator.common.utils.MMUtils; import com.recursive_pineapple.matter_manipulator.common.utils.Mods; public class EntityItemLarge extends EntityItem { public EntityItemLarge(World worldIn, double x, double y, double z, ItemStack stack) { super(worldIn, x, y, z, stack); motionX = 0; motionY = 0; motionZ = 0; } public static void registerCommon() { EntityRegistry.registerModEntity( EntityItemLarge.class, "EntityItemLarge", EntityID.LargeItem.ID, Mods.MatterManipulator.ID, 64, 3, true ); } @SideOnly(Side.CLIENT) public static void registerClient() { RenderingRegistry.registerEntityRenderingHandler(EntityItemLarge.class, new RenderItem()); } @Override public void writeEntityToNBT(NBTTagCompound tagCompound) { super.writeEntityToNBT(tagCompound); ItemStack item = this.getEntityItem(); if (item != null) { tagCompound.getCompoundTag("Item") .setInteger("Count", item.stackSize); } } @Override public void readEntityFromNBT(NBTTagCompound tagCompound) { super.readEntityFromNBT(tagCompound); isDead = false; NBTTagCompound itemTag = tagCompound.getCompoundTag("Item"); ItemStack item = ItemStack.loadItemStackFromNBT(itemTag); item.stackSize = itemTag.getInteger("Count"); this.setEntityItemStack(item); item = getDataWatcher().getWatchableObjectItemStack(10); if (item == null || item.stackSize <= 0) { this.setDead(); } } @Override public void onCollideWithPlayer(EntityPlayer player) { if (!this.worldObj.isRemote) { if (this.delayBeforeCanPickup > 0) { return; } EntityItemPickupEvent event = new EntityItemPickupEvent(player, this); if (MinecraftForge.EVENT_BUS.post(event)) { return; } player.openContainer.detectAndSendChanges(); player.inventoryContainer.detectAndSendChanges(); ItemStack itemstack = this.getEntityItem(); int i = itemstack.stackSize; if ( this.delayBeforeCanPickup <= 0 && (func_145798_i() == null || lifespan - this.age <= 200 || func_145798_i().equals(player.getCommandSenderName())) ) { player.inventory.addItemStackToInventory(itemstack); if (i == itemstack.stackSize) { // couldn't store any items return; } setEntityItemStack(itemstack); FMLCommonHandler.instance() .firePlayerItemPickupEvent(player, this); this.worldObj.playSoundAtEntity( player, "random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F ); // this just barely doesn't work, but it fixes the desync mostly so it's good enough player.openContainer.detectAndSendChanges(); player.inventoryContainer.detectAndSendChanges(); if (itemstack.stackSize <= 0) { player.onItemPickup(this, i - itemstack.stackSize); this.setDead(); } } } } @Override public boolean combineItems(EntityItem other) { if (other == this) return false; if (!other.isEntityAlive() || !this.isEntityAlive()) return false; if (!(other instanceof EntityItemLarge)) return false; ItemStack ours = this.getEntityItem(); ItemStack theirs = other.getEntityItem(); if (!MMUtils.areStacksBasicallyEqual(ours, theirs)) { return false; } if (theirs.stackSize < ours.stackSize) { return other.combineItems(this); } theirs.stackSize += ours.stackSize; other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup); other.age = Math.min(other.age, this.age); other.setEntityItemStack(theirs); this.setDead(); return true; } /** * Looks for other itemstacks nearby and tries to stack them together */ public void searchForOtherItemsNearbyCustom() { Iterator<EntityItemLarge> iterator = this.worldObj.getEntitiesWithinAABB(EntityItemLarge.class, this.boundingBox.expand(2D, 0.0D, 2D)).iterator(); while (iterator.hasNext()) { this.combineItems(iterator.next()); } Iterator<EntityPlayer> iterator2 = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, this.boundingBox.expand(2D, 0.0D, 2D)).iterator(); while (iterator2.hasNext()) { this.onCollideWithPlayer(iterator2.next()); } } }
0
0.89666
1
0.89666
game-dev
MEDIA
0.997772
game-dev
0.976176
1
0.976176
beyond-aion/aion-server
2,258
game-server/data/handlers/ai/instance/aturamSkyFortress/SteamTachysphereAI.java
package ai.instance.aturamSkyFortress; import static com.aionemu.gameserver.model.DialogAction.SETPRO1; import com.aionemu.gameserver.ai.AIName; import com.aionemu.gameserver.model.DialogPage; import com.aionemu.gameserver.model.Race; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.network.aion.serverpackets.SM_PLAY_MOVIE; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.teleport.TeleportService; import com.aionemu.gameserver.skillengine.SkillEngine; import com.aionemu.gameserver.utils.PacketSendUtility; import ai.ActionItemNpcAI; /** * @author xTz */ @AIName("steam_tachysphere") public class SteamTachysphereAI extends ActionItemNpcAI { public SteamTachysphereAI(Npc owner) { super(owner); } @Override protected void handleUseItemFinish(Player player) { final QuestState qs = player.getQuestStateList().getQuestState(player.getRace().equals(Race.ELYOS) ? 18302 : 28302); if (qs == null) { PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), DialogPage.NO_RIGHT.id())); } else if (qs.getStatus() != QuestStatus.COMPLETE) { PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 10)); } else { PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 1011)); } } @Override public boolean onDialogSelect(Player player, int dialogActionId, int questId, int extendedRewardIndex) { if (dialogActionId == SETPRO1) { final QuestState qs = player.getQuestStateList().getQuestState(player.getRace().equals(Race.ELYOS) ? 18302 : 28302); if (qs != null && qs.getStatus() == QuestStatus.COMPLETE) { TeleportService.teleportTo(player, 300240000, 175.28925f, 625.1088f, 901.009f, (byte) 33); PacketSendUtility.sendPacket(player, new SM_PLAY_MOVIE(false, 0, 0, 471, false)); SkillEngine.getInstance().getSkill(player, 19502, 1, player).useNoAnimationSkill(); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(getObjectId(), 0)); } } return true; } }
0
0.930386
1
0.930386
game-dev
MEDIA
0.920797
game-dev
0.895848
1
0.895848
appleappleapple/GameOfFighting
2,091
Classes/GameString.cpp
#include "GameString.h" CCScene* GameString::scene() { CCScene *scene = CCScene::create(); GameString *layer = GameString::create(); scene->addChild(layer); return scene; } bool GameString::init() { if ( !CCLayer::init() ) { return false; } CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); //Ӹť CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "exct.png", "exct.png", this, menu_selector(GameString::menuCloseCallback)); pCloseItem->setPosition(ccp( visibleSize.width -80 ,visibleSize.height-60)); CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu, 1); //ӱ CCSprite* pSprite = CCSprite::create("enter.png"); pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); this->addChild(pSprite, 0); //Ҫʾ CCLabelTTF* pLabel=CCLabelTTF::create(ChineseString::GBKToUTF8("ֱEvankaka\nϷҪ񶷡\nӭҵ硫\nֱEvankaka\nϷҪ񶷡\nӭҵ硫\nֱEvankaka\nϷҪ񶷡"),"Arial",25); pLabel->setAnchorPoint(CCPointZero); ccColor3B color = ccc3(255,255,0); pLabel->setColor(color); pLabel->setPosition(ccp(50, -200));//YעΪ,XӦpoint[4]50Ƕ //Ʋü CCDrawNode* shap = CCDrawNode::create(); CCPoint point[4] = {ccp(50,0), ccp(400,0), ccp(400,200), ccp(50,200)};//Ըʵ޸´С shap->drawPolygon(point,4,ccc4f(255,255,255,255),0, ccc4f(255,255,255,255));//ı //// CCClippingNode* pClip = CCClippingNode::create(); pClip->setInverted(false); pClip->setStencil(shap);//һҪУҪᱨ pClip->addChild(pLabel); this->addChild(pClip); //ʼĻ CCMoveBy* moveact=CCMoveBy::create(10.0f,CCPointMake(0,400));//0.5ƶ70 CCCallFunc* callFunc=CCCallFunc::create(this,callfunc_selector(GameString::RollEnd));//صƮ CCActionInterval* act=CCSequence::create(moveact,callFunc,NULL);// pLabel->runAction(act); return true; } void GameString::RollEnd() { CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());//Ϸ } void GameString::menuCloseCallback(CCObject* pSender) { RollEnd(); }
0
0.710597
1
0.710597
game-dev
MEDIA
0.944736
game-dev
0.920672
1
0.920672
bates64/papermario-dx
1,096
src/rumble.c
#include "common.h" #include "nu/nusys.h" #include "rumble.h" // TODO: replace nustuff with defines u16 rumbleMaxDuration = 0; s32 rumbleButtons = 0; void poll_rumble(void) { nuContRmbCheck(0); nuContRmbModeSet(0, 2); } void start_rumble(s32 freq, s32 nframes) { if (gGameStatusPtr->demoState == DEMO_STATE_NONE) { if (rumbleMaxDuration != 0) { #if !VERSION_JP s32 maxFrames = rumbleMaxDuration * 2; if (nframes > maxFrames) { nframes = maxFrames; } #endif if (nuContRmbCheck(0) == 0) { nuContRmbModeSet(0, 2); nuContRmbStart(0, freq, nframes); } } } } void update_max_rumble_duration(void) { if (rumbleButtons != gGameStatusPtr->curButtons[0]) { rumbleButtons = gGameStatusPtr->curButtons[0]; reset_max_rumble_duration(); } if (rumbleMaxDuration != 0) { rumbleMaxDuration--; } } void reset_max_rumble_duration(void) { #if VERSION_JP rumbleMaxDuration = 600; #else rumbleMaxDuration = 300; #endif }
0
0.627026
1
0.627026
game-dev
MEDIA
0.75133
game-dev
0.642071
1
0.642071
magicskysword/Next
5,571
Template/ModABPackTemplate/Assets/Scripts/SkySwordKill/NextUnity/Editor/NextModPackerPanel.cs
using System; using System.IO; using UnityEditor; using UnityEngine; namespace SkySwordKill.NextUnity.Editor { public class NextModPackerPanel : EditorWindow { [MenuItem("Next工具/Mod打包器")] public static void CreateWindow() { var window = GetWindow<NextModPackerPanel>(); window.titleContent = new UnityEngine.GUIContent("NextMod打包器r"); window.Show(); } private static bool _isDirty; private NextModPackerCollection _collection; public NextModPackerCollection Collection { get { if (_collection != null) { return _collection; } _collection = AssetDatabase.LoadAssetAtPath("Assets/NextModPackerCollection.asset", typeof(NextModPackerCollection)) as NextModPackerCollection; if (_collection == null) { _collection = ScriptableObject.CreateInstance<NextModPackerCollection>(); AssetDatabase.CreateAsset(_collection, "Assets/NextModPackerCollection.asset"); AssetDatabase.SaveAssets(); } return _collection; } } private void OnGUI() { var collection = Collection; // 绘制列表 Collection EditorGUILayout.LabelField("Mod打包设置"); GUILayout.Space(10); EditorGUILayout.BeginVertical(new GUIStyle("box")); if (GUILayout.Button(EditorGUIUtility.IconContent("Toolbar Plus"), GUILayout.Width(80))) { var setting = new NextModPackerSetting(); collection.settings.Add(setting); _isDirty = true; } for (var i = 0; i < collection.settings.Count; i++) { var setting = collection.settings[i]; EditorGUILayout.BeginHorizontal(new GUIStyle("box")); { EditorGUILayout.BeginVertical(); { setting.bundleName = InputField("AB包名:", setting.bundleName); setting.assetDir = FolderInputField("文件目录:", setting.assetDir); setting.outDir = FolderInputField("输出目录:", setting.outDir); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayout.Width(80)); { if (GUILayout.Button("打包")) { DelayedCall(() => NextModPackerCore.PackToAssetBundle(setting)); } if (GUILayout.Button("测试读取")) { DelayedCall(() => NextModPackerCore.TestLoadAssetBundle(setting)); } if(GUILayout.Button("删除")) { collection.settings.RemoveAt(i); i--; _isDirty = true; } } EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); GUILayout.Space(50); if(GUILayout.Button("打包所有", GUILayout.Width(100))) { DelayedCall(() => { foreach (var setting in collection.settings) { NextModPackerCore.PackToAssetBundle(setting); } }); } if (_isDirty) { _isDirty = false; EditorUtility.SetDirty(collection); } } public static void DelayedCall(Action action) { EditorApplication.CallbackFunction func = null; func = () => { action(); EditorApplication.delayCall -= func; }; EditorApplication.delayCall += func; } public static string InputField(string title, string value) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(title, GUILayout.Width(80)); var result = EditorGUILayout.TextField(value); EditorGUILayout.EndHorizontal(); if(result != value) _isDirty = true; return result; } public static string FolderInputField(string title, string value) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(title, GUILayout.Width(80)); var result = EditorGUILayout.TextField(value); if (GUILayout.Button(EditorGUIUtility.IconContent("SettingsIcon"), GUILayout.Width(20))) { // 打开文件夹选择 var path = EditorUtility.OpenFolderPanel("选择文件夹", value, ""); if (!string.IsNullOrEmpty(path)) { result = path; } } EditorGUILayout.EndHorizontal(); if(result != value) _isDirty = true; return result; } } }
0
0.936765
1
0.936765
game-dev
MEDIA
0.663365
game-dev,desktop-app
0.971541
1
0.971541
videogamepreservation/homeworld
6,370
src/Win32/prim2d.h
/*============================================================================= Name : prim2d.h Purpose : Abstraction for drawing 2D primitives. Created 6/26/1997 by lmoloney Copyright Relic Entertainment, Inc. All rights reserved. =============================================================================*/ #ifndef ___PRIM2D_H #define ___PRIM2D_H #include "types.h" #include "color.h" #include "main.h" /*============================================================================= Functions: =============================================================================*/ #ifndef HW_Release #define PRIM_ERROR_CHECKING 1 //general error checking #else //HW_Debug #define PRIM_ERROR_CHECKING 0 //general error checking #endif //HW_Debug /*============================================================================= Define: =============================================================================*/ #define P2_OvalSegments 16 /*============================================================================= Type definitions: =============================================================================*/ //basic 2D rectangle typedef struct { sdword x0, y0, x1, y1; } rectangle; //basic 2D rectangle typedef struct { real32 x0, y0, x1, y1; } realrectangle; //basic triangle structure typedef struct { sdword x0, y0, x1, y1, x2, y2; } triangle; //basic oval structure typedef struct { sdword centreX, centreY; sdword radiusX, radiusY; } oval; /*============================================================================= Data: =============================================================================*/ extern sdword primModeEnabled; /*============================================================================= Macros: =============================================================================*/ #define primModeSet2() if (!primModeEnabled) primModeSetFunction2(); #define primModeClear2() if (primModeEnabled) primModeClearFunction2(); #define primScreenToGLX(x) (((real32)(x)+0.325f) / (real32)(MAIN_WindowWidth) * 2.0f - 1.0f) #define primScreenToGLY(y) (1.0f - ((real32)(y)+0.325f) / (real32)(MAIN_WindowHeight) * 2.0f) #define primScreenToGLScaleX(x) ((real32)(x) / (real32)(MAIN_WindowWidth) * 2.0f) #define primScreenToGLScaleY(y) ((real32)(y) / (real32)(MAIN_WindowHeight) * 2.0f) #define primGLToScreenX(x) (MAIN_WindowWidth / 2 + (sdword)((x) * (real32)MAIN_WindowWidth / 2.0f)) #define primGLToScreenY(y) (MAIN_WindowHeight / 2 - (sdword)((y) * (real32)MAIN_WindowHeight / 2.0f)) #define primGLToScreenScaleX(x) ((sdword)((x) * (real32)MAIN_WindowWidth / 2.0f)) #define primGLToScreenScaleY(y) ((sdword)((y) * (real32)MAIN_WindowHeight / 2.0f)) #define primPointInRectXY2(r, x, y) ((x) >= (r)->x0 && (y) >= (r)->y0 && \ (x) < (r)->x1 && (y) < (r)->y1) #if PRIM_ERROR_CHECKING #define primErrorMessagePrint() primErrorMessagePrintFunction(__FILE__, __LINE__) #else #define primErrorMessagePrint() #endif /*============================================================================= Functions: =============================================================================*/ //enable/disable primitive drawing mode do not call directly, use macros instead void primModeSetFunction2(void); void primModeClearFunction2(void); //draw a single colored triangle void primTriSolid2(triangle *tri, color c); void primTriOutline2(triangle *tri, sdword thickness, color c); //draw a rectangle void primRectSolid2(rectangle *rect, color c); void primRectTranslucent2(rectangle *rect, color c); void primBeveledRectSolid(rectangle *rect, color c, uword xb, uword yb); void primRectOutline2(rectangle *rect, sdword thickness, color c); void primBeveledRectOutline(rectangle *rect, sdword thickness, color c, uword xb, uword yb); void primRoundRectOutline(rectangle *rect, sdword thickness, color c, uword xb, uword yb); void primRectShaded2(rectangle *rect, color *c); // color *c is a pointer to an array of 4 color values #define OL_UL 0x01 #define OL_UR 0x02 #define OL_LR 0x04 #define OL_LL 0x08 #define OL_ALL 0x0F void primMaskedRoundRectOutline(rectangle *rect, sdword thickness, color c, uword xb, uword yb, uword mask); void primRectSolidTextured2(rectangle *rect); void primRectSolidTexturedFullRect2(rectangle *rect); void primRectSolidTexturedFullRectC2(rectangle *rect, color c); //draw a line void primLine2(sdword x0, sdword y0, sdword x1, sdword y1, color c); void primNonAALine2(sdword x0, sdword y0, sdword x1, sdword y1, color c); void primLineThick2(sdword x0, sdword y0, sdword x1, sdword y1, sdword thickness, color c); //draw a line loop void primLineLoopStart2(sdword thickness, color c); void primLineLoopPoint3F(real32 x, real32 y); void primLineLoopEnd2(void); //draw solid circular things void primCircleSolid2(sdword x, sdword y, sdword rad, sdword nSlices, color c); void primCircleBorder(sdword x, sdword y, sdword radInner, sdword radOuter, sdword nSlices, color colInner); //2d rectangle utility functions void primRectUnion2(rectangle *result, rectangle *r0, rectangle *r1); void primRealRectUnion2(realrectangle *result, realrectangle *r0, realrectangle *r1); //draw oval arcs void primOvalArcOutline2(oval *o, real32 radStart, real32 radEnd, sdword thickness, sdword segments, color c); void primGLCircleOutline2(real32 x, real32 y, real32 radius, sdword nSegments, color c); //series of successively blended rect outlines void primSeriesOfRects(rectangle *rect, uword width, color fore, color back, uword steps); void primSeriesOfBeveledRects(rectangle *rect, uword width, color fore, color back, uword steps, uword xb, uword yb); void primSeriesOfRoundRects(rectangle *rect, uword width, color fore, color back, uword steps, uword xb, uword yb); //points void primBlurryPoint2(sdword x, sdword y, color c); void primBlurryPoint22(sdword x, sdword y, color c); //report errors void primErrorMessagePrintFunction(char *file, sdword line); //utility functions real32 primPointLineIntersection(real32 xp, real32 yp, real32 x0, real32 y0, real32 x1, real32 y1); #endif //___PRIM2D_H
0
0.933356
1
0.933356
game-dev
MEDIA
0.554014
game-dev
0.893071
1
0.893071
gschup/bevy_ggrs
6,857
examples/box_game/box_game.rs
use bevy::{platform::collections::HashMap, prelude::*}; use bevy_ggrs::{ AddRollbackCommandExtension, GgrsConfig, LocalInputs, LocalPlayers, PlayerInputs, Rollback, Session, }; use serde::{Deserialize, Serialize}; use std::hash::Hash; const BLUE: Color = Color::srgb(0.8, 0.6, 0.2); const ORANGE: Color = Color::srgb(0., 0.35, 0.8); const MAGENTA: Color = Color::srgb(0.9, 0.2, 0.2); const GREEN: Color = Color::srgb(0.35, 0.7, 0.35); const PLAYER_COLORS: [Color; 4] = [BLUE, ORANGE, MAGENTA, GREEN]; const INPUT_UP: u8 = 1 << 0; const INPUT_DOWN: u8 = 1 << 1; const INPUT_LEFT: u8 = 1 << 2; const INPUT_RIGHT: u8 = 1 << 3; const ACCELERATION: f32 = 18.0; const MAX_SPEED: f32 = 3.0; const FRICTION: f32 = 0.0018; const PLANE_SIZE: f32 = 5.0; const CUBE_SIZE: f32 = 0.2; // You need to define a config struct to bundle all the generics of GGRS. bevy_ggrs provides a sensible default in `GgrsConfig`. // (optional) You can define a type here for brevity. pub type BoxConfig = GgrsConfig<BoxInput>; #[repr(C)] #[derive(Copy, Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct BoxInput(u8); #[derive(Default, Component)] pub struct Player { pub handle: usize, } // Components that should be saved/loaded need to support snapshotting. The built-in options are: // - Clone (Recommended) // - Copy // - Reflect // See `bevy_ggrs::Strategy` for custom alternatives #[derive(Default, Reflect, Component, Clone, Copy, Deref, DerefMut)] pub struct Velocity(pub Vec3); // You can also register resources. #[derive(Resource, Default, Reflect, Hash, Clone, Copy)] #[reflect(Hash)] pub struct FrameCount { pub frame: u32, } /// Collects player inputs during [`ReadInputs`](`bevy_ggrs::ReadInputs`) and creates a [`LocalInputs`] resource. pub fn read_local_inputs( mut commands: Commands, keyboard_input: Res<ButtonInput<KeyCode>>, local_players: Res<LocalPlayers>, ) { let mut local_inputs = HashMap::new(); for handle in &local_players.0 { let mut input: u8 = 0; if keyboard_input.pressed(KeyCode::KeyW) { input |= INPUT_UP; } if keyboard_input.pressed(KeyCode::KeyA) { input |= INPUT_LEFT; } if keyboard_input.pressed(KeyCode::KeyS) { input |= INPUT_DOWN; } if keyboard_input.pressed(KeyCode::KeyD) { input |= INPUT_RIGHT; } local_inputs.insert(*handle, BoxInput(input)); } commands.insert_resource(LocalInputs::<BoxConfig>(local_inputs)); } pub fn setup_system( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, session: Res<Session<BoxConfig>>, ) { let num_players = match &*session { Session::SyncTest(s) => s.num_players(), Session::P2P(s) => s.num_players(), Session::Spectator(s) => s.num_players(), }; // A ground plane commands.spawn(( Mesh3d(meshes.add(Plane3d::new(Vec3::Y, Vec2::splat(PLANE_SIZE / 2.0)))), MeshMaterial3d(materials.add(StandardMaterial::from(Color::srgb(0.3, 0.5, 0.3)))), )); let r = PLANE_SIZE / 4.; let mesh = meshes.add(Cuboid::from_length(CUBE_SIZE)); for handle in 0..num_players { let rot = handle as f32 / num_players as f32 * 2. * std::f32::consts::PI; let x = r * rot.cos(); let z = r * rot.sin(); let mut transform = Transform::default(); transform.translation.x = x; transform.translation.y = CUBE_SIZE / 2.; transform.translation.z = z; let color = PLAYER_COLORS[handle % PLAYER_COLORS.len()]; // Entities which will be rolled back can be created just like any other... commands .spawn(( // ...add visual information... Mesh3d(mesh.clone()), MeshMaterial3d(materials.add(StandardMaterial::from(color))), transform, // ...flags... Player { handle }, // ...and components which will be rolled-back... Velocity::default(), )) // ...just ensure you call `add_rollback()` // This ensures a stable ID is available for the rollback system to refer to .add_rollback(); } // light commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 8.0, 4.0))); // camera commands.spawn(( Camera3d::default(), Transform::from_xyz(0.0, 7.5, 0.5).looking_at(Vec3::ZERO, Vec3::Y), )); } // Example system, manipulating a resource, will be added to the rollback schedule. // Increases the frame count by 1 every update step. If loading and saving resources works correctly, // you should see this resource rolling back, counting back up and finally increasing by 1 every update step #[allow(dead_code)] pub fn increase_frame_system(mut frame_count: ResMut<FrameCount>) { frame_count.frame += 1; } // Example system that moves the cubes, will be added to the rollback schedule. // Filtering for the rollback component is a good way to make sure your game logic systems // only mutate components that are being saved/loaded. #[allow(dead_code)] pub fn move_cube_system( mut query: Query<(&mut Transform, &mut Velocity, &Player), With<Rollback>>, // ^------^ Added by `add_rollback` earlier inputs: Res<PlayerInputs<BoxConfig>>, // Thanks to RollbackTimePlugin, this is rollback safe time: Res<Time>, ) { let dt = time.delta().as_secs_f32(); for (mut t, mut v, p) in query.iter_mut() { let input = inputs[p.handle].0.0; // set velocity through key presses if input & INPUT_UP != 0 && input & INPUT_DOWN == 0 { v.z -= ACCELERATION * dt; } if input & INPUT_UP == 0 && input & INPUT_DOWN != 0 { v.z += ACCELERATION * dt; } if input & INPUT_LEFT != 0 && input & INPUT_RIGHT == 0 { v.x -= ACCELERATION * dt; } if input & INPUT_LEFT == 0 && input & INPUT_RIGHT != 0 { v.x += ACCELERATION * dt; } // slow down if input & INPUT_UP == 0 && input & INPUT_DOWN == 0 { v.z *= FRICTION.powf(dt); } if input & INPUT_LEFT == 0 && input & INPUT_RIGHT == 0 { v.x *= FRICTION.powf(dt); } v.y *= FRICTION.powf(dt); // constrain velocity **v = v.clamp_length_max(MAX_SPEED); // apply velocity t.translation += **v * dt; // constrain cube to plane let half_width = (PLANE_SIZE - CUBE_SIZE) * 0.5; t.translation.x = t.translation.x.clamp(-half_width, half_width); t.translation.z = t.translation.z.clamp(-half_width, half_width); } }
0
0.946473
1
0.946473
game-dev
MEDIA
0.835836
game-dev
0.931044
1
0.931044
stephomi/sculptgl
17,916
src/editing/Reversion.js
import Utils from 'misc/Utils'; var Reversion = {}; var detectExtraordinaryVertices = function (mesh) { var nbVertices = mesh.getNbVertices(); var fAr = mesh.getFaces(); var onEdge = mesh.getVerticesOnEdge(); var vrvStartCount = mesh.getVerticesRingVertStartCount(); var vrf = mesh.getVerticesRingFace(); var vrfStartCount = mesh.getVerticesRingFaceStartCount(); var vExtraTags = new Int8Array(nbVertices); for (var i = 0; i < nbVertices; ++i) { var id = i * 2; var len = vrvStartCount[id + 1]; var startFace = vrfStartCount[id]; var countFace = vrfStartCount[id + 1]; var vBorder = onEdge[i]; var nbQuad = 0; for (var j = startFace, endFace = startFace + countFace; j < endFace; ++j) { nbQuad += fAr[vrf[j] * 4 + 3] === Utils.TRI_INDEX ? 0 : 1; } if (nbQuad === 0) { // tris if ((!vBorder && len !== 6) || (vBorder && len !== 4)) vExtraTags[i] = 1; } else if (nbQuad === countFace) { // quads if ((!vBorder && len !== 4) || (vBorder && len !== 3)) vExtraTags[i] = 1; } else { // quad and tri if (vBorder || len !== 5) vExtraTags[i] = 1; } } return vExtraTags; }; /** Return the first extraordinary vertex if it exists... or a random vertex otherwise */ var getSeed = function (mesh, vEvenTags, vExtraTags) { var i = 0; var nbVertices = mesh.getNbVertices(); for (i = 0; i < nbVertices; ++i) { if (vEvenTags[i] !== 0) continue; if (vExtraTags[i] === 1) return i; } // no extraordinary vertices... var onEdge = mesh.getVerticesOnEdge(); for (i = 0; i < nbVertices; ++i) { if (vEvenTags[i] !== 0) continue; // skip already processed vertex if (onEdge[i] !== 1) break; } // cancels reversion if there is no edge vertex if (i === nbVertices) return -1; // find the first non-already processed vertex for (i = 0; i < nbVertices; ++i) { if (vEvenTags[i] === 0) return i; } return -1; }; /** Tag the even vertices */ var tagVertices = function (mesh, vExtraTags, vEvenTags) { var tagFlag = ++Utils.TAG_FLAG; var vFlags = mesh.getVerticesTagFlags(); var vrvSC = mesh.getVerticesRingVertStartCount(); var vrv = mesh.getVerticesRingVert(); var onEdge = mesh.getVerticesOnEdge(); var vSeed = getSeed(mesh, vEvenTags, vExtraTags); if (vSeed < 0) return false; vEvenTags[vSeed] = 1; var stack = new Uint32Array(Utils.getMemory(mesh.getNbVertices() * 4), 0, mesh.getNbVertices()); stack[0] = vSeed; var curStack = 1; while (curStack > 0) { var idVert = stack[--curStack]; var start = vrvSC[idVert * 2]; var end = start + vrvSC[idVert * 2 + 1]; var i = 0; var stamp = ++tagFlag; // tag the odd vertices for (i = start; i < end; ++i) { var oddi = vrv[i]; vFlags[oddi] = stamp; // already an even vertex if (vEvenTags[oddi] === 1) { Utils.TAG_FLAG = tagFlag; return false; } vEvenTags[oddi] = -1; //odd vertex vFlags[oddi] = stamp; } // stamp-1 means odd vertex, while stamp ==> locally already // visited candidates opposites even vertex stamp = ++tagFlag; for (i = start; i < end; ++i) { var oddId = vrv[i]; // extraordinary vertex marked as odd vertex if (vExtraTags[oddId] !== 0 && !onEdge[oddId]) { Utils.TAG_FLAG = tagFlag; return false; } var oddStart = vrvSC[oddId * 2]; var oddEnd = oddStart + vrvSC[oddId * 2 + 1]; // find opposite vertex for (var j = oddStart; j < oddEnd; ++j) { var evenj = vrv[j]; if (evenj === idVert) continue; if (vFlags[evenj] >= (stamp - 1)) // see comments above continue; vFlags[evenj] = stamp; if (vEvenTags[evenj] !== 0) // already processed continue; var oppStart = vrvSC[evenj * 2]; var oppEnd = oppStart + vrvSC[evenj * 2 + 1]; var nbOdd = 0; for (var k = oppStart; k < oppEnd; ++k) { if (vFlags[vrv[k]] === (stamp - 1)) nbOdd++; } if (nbOdd === 2) { vEvenTags[evenj] = -1; } else { vEvenTags[evenj] = 1; stack[curStack++] = evenj; } } } } Utils.TAG_FLAG = tagFlag; return true; }; /** Tag the even vertices */ var tagEvenVertices = function (mesh, vEvenTags) { var nbVertices = mesh.getNbVertices(); var vExtraTags = detectExtraordinaryVertices(mesh); var running = true; while (running) { if (!tagVertices(mesh, vExtraTags, vEvenTags)) return false; running = false; for (var i = 0; i < nbVertices; ++i) { if (vEvenTags[i] === 0) { running = true; break; } } } return true; }; /** Creates the coarse faces from the tagged vertices */ var createFaces = function (baseMesh, newMesh, vEvenTags, triFaceOrQuadCenter) { var feAr = baseMesh.getFaceEdges(); var fArUp = baseMesh.getFaces(); var tagEdges = new Int32Array(baseMesh.getNbEdges()); var i = 0; var nbFaces = baseMesh.getNbFaces(); var acc = 0; var centerQuadUp = new Uint32Array(baseMesh.getNbVertices()); var fArDown = new Uint32Array(nbFaces); for (i = 0; i < nbFaces; ++i) fArDown[i] = Utils.TRI_INDEX; for (i = 0; i < nbFaces; ++i) { var j = i * 4; var iv1 = fArUp[j]; var iv2 = fArUp[j + 1]; var iv3 = fArUp[j + 2]; var iv4 = fArUp[j + 3]; var tag1 = vEvenTags[iv1]; var tag2 = vEvenTags[iv2]; var tag3 = vEvenTags[iv3]; if (iv4 === Utils.TRI_INDEX) { // center tri if (tag1 + tag2 + tag3 === -3) { triFaceOrQuadCenter[acc++] = i; continue; } // tri if (tag1 === 1) tagEdges[feAr[j + 1]] = iv1 + 1; else if (tag2 === 1) tagEdges[feAr[j + 2]] = iv2 + 1; else if (tag3 === 1) tagEdges[feAr[j]] = iv3 + 1; continue; } //quad var ivCorner = 0; var ivCenter = 0; var oppEdge = 0; if (tag1 === 1) { ivCorner = iv1; ivCenter = iv3; oppEdge = tagEdges[feAr[j + 1]] - 1; tagEdges[feAr[j + 2]] = iv1 + 1; } else if (tag2 === 1) { ivCorner = iv2; ivCenter = iv4; oppEdge = tagEdges[feAr[j + 2]] - 1; tagEdges[feAr[j + 3]] = iv2 + 1; } else if (tag3 === 1) { ivCorner = iv3; ivCenter = iv1; oppEdge = tagEdges[feAr[j + 3]] - 1; tagEdges[feAr[j]] = iv3 + 1; } else { ivCorner = iv4; ivCenter = iv2; oppEdge = tagEdges[feAr[j]] - 1; tagEdges[feAr[j + 1]] = iv4 + 1; } var quad = centerQuadUp[ivCenter] - 1; if (quad < 0) { triFaceOrQuadCenter[acc] = -ivCenter - 1; fArDown[acc * 4 + 3] = ivCorner; centerQuadUp[ivCenter] = ++acc; continue; } var idQuad = quad * 4; if (oppEdge < 0) { // no opposite edge if (fArDown[idQuad + 2] >= (Utils.TRI_INDEX - 1)) { fArDown[idQuad + 2] = ivCorner; fArDown[idQuad] = Utils.TRI_INDEX - 1; } else if (fArDown[idQuad] === Utils.TRI_INDEX) { fArDown[idQuad + 1] = ivCorner; } else { fArDown[idQuad + 1] = fArDown[idQuad + 2]; fArDown[idQuad + 2] = ivCorner; } } else { // insert after oppEdge if (fArDown[idQuad + 1] === oppEdge) { fArDown[idQuad] = ivCorner; } else { fArDown[idQuad] = fArDown[idQuad + 1]; if (fArDown[idQuad + 2] === oppEdge) { fArDown[idQuad + 1] = ivCorner; } else { fArDown[idQuad + 1] = fArDown[idQuad + 2]; fArDown[idQuad + 2] = ivCorner; } } } } nbFaces /= 4; for (i = 0; i < nbFaces; ++i) { var cen = triFaceOrQuadCenter[i]; var idFace = i * 4; if (cen < 0) { // quad // Sometimes... the way we revert quads does not always work // because of non-consistency clock wise order between neighbor quads var cmp = Utils.TRI_INDEX - 1; if (fArDown[idFace] >= cmp || fArDown[idFace + 1] >= Utils.TRI_INDEX || fArDown[idFace + 2] >= Utils.TRI_INDEX) return false; continue; } // tri var id = cen * 4; fArDown[idFace] = tagEdges[feAr[id]] - 1; fArDown[idFace + 1] = tagEdges[feAr[id + 1]] - 1; fArDown[idFace + 2] = tagEdges[feAr[id + 2]] - 1; } newMesh.setFaces(fArDown); return true; }; /** Creates the vertices of the mesh */ var createVertices = function (baseMesh, newMesh, triFaceOrQuadCenter) { var acc = 0; var vertexMapUp = new Uint32Array(baseMesh.getNbVertices()); newMesh.setVerticesMapping(vertexMapUp); var fArDown = newMesh.getFaces(); var tagVert = new Int32Array(baseMesh.getNbVertices()); var i = 0; var len = newMesh.getNbFaces() * 4; for (i = 0; i < len; ++i) { var iv = fArDown[i]; if (iv === Utils.TRI_INDEX) continue; var tag = tagVert[iv] - 1; if (tag === -1) { tag = acc++; tagVert[iv] = tag + 1; vertexMapUp[tag] = iv; } fArDown[i] = tag; } newMesh.setVertices(new Float32Array(acc * 3)); var fArUp = baseMesh.getFaces(); var vrf = baseMesh.getVerticesRingFace(); var vrfStartCount = baseMesh.getVerticesRingFaceStartCount(); var tagMid = new Uint8Array(baseMesh.getNbVertices()); len /= 4; for (i = 0; i < len; ++i) { var iCenter = triFaceOrQuadCenter[i]; var mid1, mid2, mid3, mid4, mid5; var tag1, tag2, tag3, tag4, tag5; if (iCenter >= 0) { // tri var id = iCenter * 4; mid1 = fArUp[id + 1]; mid2 = fArUp[id + 2]; mid3 = fArUp[id]; mid4 = Utils.TRI_INDEX; mid5 = Utils.TRI_INDEX; } else { // quad mid5 = -iCenter - 1; var idQuadDown = i * 4; var corner1 = vertexMapUp[fArDown[idQuadDown]]; var corner2 = vertexMapUp[fArDown[idQuadDown + 1]]; var corner3 = vertexMapUp[fArDown[idQuadDown + 2]]; var corner4 = vertexMapUp[fArDown[idQuadDown + 3]]; var start = vrfStartCount[mid5 * 2]; var end = start + 4; for (var j = start; j < end; ++j) { var idQuad = vrf[j] * 4; var id1 = fArUp[idQuad]; var id2 = fArUp[idQuad + 1]; var id3 = fArUp[idQuad + 2]; var id4 = fArUp[idQuad + 3]; if (id1 === corner1) mid1 = id2; else if (id2 === corner1) mid1 = id3; else if (id3 === corner1) mid1 = id4; else if (id4 === corner1) mid1 = id1; if (id1 === corner2) mid2 = id2; else if (id2 === corner2) mid2 = id3; else if (id3 === corner2) mid2 = id4; else if (id4 === corner2) mid2 = id1; if (id1 === corner3) mid3 = id2; else if (id2 === corner3) mid3 = id3; else if (id3 === corner3) mid3 = id4; else if (id4 === corner3) mid3 = id1; if (id1 === corner4) mid4 = id2; else if (id2 === corner4) mid4 = id3; else if (id3 === corner4) mid4 = id4; else if (id4 === corner4) mid4 = id1; } } tag1 = tagMid[mid1]; tag2 = tagMid[mid2]; tag3 = tagMid[mid3]; tag4 = mid4 !== Utils.TRI_INDEX ? tagMid[mid4] : -1; tag5 = mid5 !== Utils.TRI_INDEX ? tagMid[mid5] : -1; if (tag1 === 0) { tagMid[mid1] = 1; vertexMapUp[acc++] = mid1; } if (tag2 === 0) { tagMid[mid2] = 1; vertexMapUp[acc++] = mid2; } if (tag3 === 0) { tagMid[mid3] = 1; vertexMapUp[acc++] = mid3; } if (tag4 === 0) { tagMid[mid4] = 1; vertexMapUp[acc++] = mid4; } if (tag5 === 0) { tagMid[mid5] = 1; vertexMapUp[acc++] = mid5; } } }; /** Copy the vertices data from up to low */ var copyVerticesData = function (baseMesh, newMesh) { var vArUp = baseMesh.getVertices(); var cArUp = baseMesh.getColors(); var mArUp = baseMesh.getMaterials(); var vArDown = newMesh.getVertices(); var cArDown = new Float32Array(vArDown.length); var mArDown = new Float32Array(vArDown.length); newMesh.setColors(cArDown); newMesh.setMaterials(mArDown); var vertexMapUp = newMesh.getVerticesMapping(); var i = 0; var nbVertices = newMesh.getNbVertices(); for (i = 0; i < nbVertices; ++i) { if (vertexMapUp[i] >= nbVertices) break; } if (i === nbVertices) { // we don't have to keep the vertex mapping var fArDown = newMesh.getFaces(); var nb = fArDown.length; for (i = 0; i < nb; ++i) { var idv = fArDown[i]; if (idv !== Utils.TRI_INDEX) fArDown[i] = vertexMapUp[idv]; } // direct mapping for even vertices for (i = 0; i < nbVertices; ++i) vertexMapUp[i] = i; vArDown.set(vArUp.subarray(0, nbVertices * 3)); cArDown.set(cArUp.subarray(0, nbVertices * 3)); mArDown.set(mArUp.subarray(0, nbVertices * 3)); } else { // we keep the vertex mapping newMesh.setEvenMapping(true); for (i = 0; i < nbVertices; ++i) { var id = i * 3; var idUp = vertexMapUp[i] * 3; vArDown[id] = vArUp[idUp]; vArDown[id + 1] = vArUp[idUp + 1]; vArDown[id + 2] = vArUp[idUp + 2]; cArDown[id] = cArUp[idUp]; cArDown[id + 1] = cArUp[idUp + 1]; cArDown[id + 2] = cArUp[idUp + 2]; mArDown[id] = mArUp[idUp]; mArDown[id + 1] = mArUp[idUp + 1]; mArDown[id + 2] = mArUp[idUp + 2]; } } }; /** Computes uv faces and uv coordinates for center vertices */ var computeFaceTexCoords = function (baseMesh, newMesh, triFaceOrQuadCenter, uvMap) { var fArUp = baseMesh.getFaces(); var fArUVUp = baseMesh.getFacesTexCoord(); var vrfSC = baseMesh.getVerticesRingFaceStartCount(); var vrf = baseMesh.getVerticesRingFace(); var dupUp = baseMesh.getVerticesDuplicateStartCount(); var fAr = newMesh.getFaces(); var fArUV = new Uint32Array(fAr); var vertexMapUp = newMesh.getVerticesMapping(); for (var i = 0, len = fAr.length; i < len; ++i) { var iv = fAr[i]; if (iv === Utils.TRI_INDEX) continue; var ivUp = vertexMapUp[iv]; if (dupUp[ivUp * 2] === 0) continue; // vertex with duplicates var index = i % 4; var iCen = triFaceOrQuadCenter[(i - index) / 4]; var vertUV = Utils.TRI_INDEX; if (iCen >= 0) { // tri var idCen = iCen * 4; var mid1, mid2; if (index === 0) { mid1 = fArUp[idCen + 1]; mid2 = fArUp[idCen]; } else if (index === 1) { mid1 = fArUp[idCen + 2]; mid2 = fArUp[idCen + 1]; } else { mid1 = fArUp[idCen]; mid2 = fArUp[idCen + 2]; } var startTri = vrfSC[ivUp * 2]; var endTri = startTri + vrfSC[ivUp * 2 + 1]; for (var idt = startTri; idt < endTri; ++idt) { var idTri = vrf[idt] * 4; var idMid1 = fArUp[idTri]; var idMid2 = fArUp[idTri + 1]; var idMid3 = fArUp[idTri + 2]; if (idMid1 === mid1) { if (idMid2 === mid2) vertUV = fArUVUp[idTri + 2]; } else if (idMid2 === mid1) { if (idMid3 === mid2) vertUV = fArUVUp[idTri]; } else if (idMid3 === mid1) { if (idMid1 === mid2) vertUV = fArUVUp[idTri + 1]; } if (vertUV !== Utils.TRI_INDEX) break; } } else { // quad iCen = -iCen - 1; var startQuad = vrfSC[iCen * 2]; var endQuad = startQuad + 4; for (var idq = startQuad; idq < endQuad; ++idq) { var idQuad = vrf[idq] * 4; if (fArUp[idQuad] === ivUp) vertUV = fArUVUp[idQuad]; else if (fArUp[idQuad + 1] === ivUp) vertUV = fArUVUp[idQuad + 1]; else if (fArUp[idQuad + 2] === ivUp) vertUV = fArUVUp[idQuad + 2]; else if (fArUp[idQuad + 3] === ivUp) vertUV = fArUVUp[idQuad + 3]; if (vertUV !== Utils.TRI_INDEX) break; } } fArUV[i] = vertUV === ivUp ? vertUV : vertUV - uvMap[iv]; } newMesh.setFacesTexCoord(fArUV); }; /** Apply the reverse of a subdivision for the texCoord mesh */ var computeTexCoords = function (baseMesh, newMesh, triFaceOrQuadCenter) { var dupUp = baseMesh.getVerticesDuplicateStartCount(); var nbVertices = newMesh.getNbVertices(); var dup = new Uint32Array(nbVertices * 2); var vertexMapUp = newMesh.getVerticesMapping(); var uvArUp = baseMesh.getTexCoords(); var uvAr = new Float32Array(Utils.getMemory(baseMesh.getNbTexCoords() * 4 * 2), 0, baseMesh.getNbTexCoords() * 2); var uvMap = new Uint32Array(nbVertices); var nbTexCoords = nbVertices; for (var i = 0; i < nbVertices; ++i) { var ivUp = vertexMapUp[i]; var start = dupUp[ivUp * 2]; uvAr[i * 2] = uvArUp[ivUp * 2]; uvAr[i * 2 + 1] = uvArUp[ivUp * 2 + 1]; if (start === 0) continue; // vertex with duplicates var startOld = uvMap[i] = start - nbTexCoords; var nbDupl = dupUp[ivUp * 2 + 1]; for (var j = nbTexCoords, end = nbTexCoords + nbDupl; j < end; ++j) { uvAr[j * 2] = uvArUp[(startOld + j) * 2]; uvAr[j * 2 + 1] = uvArUp[(startOld + j) * 2 + 1]; } dup[i * 2] = nbTexCoords; dup[i * 2 + 1] = nbDupl; nbTexCoords += nbDupl; } newMesh.setTexCoords(new Float32Array(uvAr.subarray(0, nbTexCoords * 2))); newMesh.setVerticesDuplicateStartCount(dup); computeFaceTexCoords(baseMesh, newMesh, triFaceOrQuadCenter, uvMap); }; /** Apply the reverse of a subdivision */ Reversion.computeReverse = function (baseMesh, newMesh) { var nbFaces = baseMesh.getNbFaces(); if (nbFaces % 4 !== 0) return false; // 0 not processed, -1 odd vertex, 1 even vertex var vEvenTags = new Int8Array(baseMesh.getNbVertices()); if (!tagEvenVertices(baseMesh, vEvenTags)) return false; var triFaceOrQuadCenter = new Int32Array(nbFaces / 4); if (!createFaces(baseMesh, newMesh, vEvenTags, triFaceOrQuadCenter)) return false; createVertices(baseMesh, newMesh, triFaceOrQuadCenter); copyVerticesData(baseMesh, newMesh); if (baseMesh.hasUV()) computeTexCoords(baseMesh, newMesh, triFaceOrQuadCenter); newMesh.allocateArrays(); return true; }; export default Reversion;
0
0.653413
1
0.653413
game-dev
MEDIA
0.949619
game-dev
0.977579
1
0.977579
exmex/UnityMoba
1,836
Assets/Lua/Logic/M103/BountyMatchGetReward/BountyMatchGetRewardAPI.lua
--author zx class("BountyMatchGetRewardAPI") function BountyMatchGetRewardAPI:Awake(this) self.this = this BountyMatchGetRewardAPI.Instance = self self.main = self.this.transforms[0] --self.ctrl = self.this.transforms[0]:GetComponent("NTGLuaScript") self:SetFxOk(self.main) end function BountyMatchGetRewardAPI:Start() end function BountyMatchGetRewardAPI:Init(itemId) local itemData = UTGData.Instance().ItemsData[tostring(itemId)] local listener = {} listener = NTGEventTriggerProxy.Get(self.main:FindChild("But-Close").gameObject) listener.onPointerClick = NTGEventTriggerProxy.PointerEventDelegateSelf(self.ClosePanel,self) listener = NTGEventTriggerProxy.Get(self.main:FindChild("But-Yes").gameObject) listener.onPointerClick = NTGEventTriggerProxy.PointerEventDelegateSelf(self.ClosePanel,self) self.main:FindChild("Bg"):GetComponent("UnityEngine.UI.Image").sprite = UITools.GetSprite("icon",itemData.Quality) self.main:FindChild("Icon"):GetComponent("UnityEngine.UI.Image").sprite = UITools.GetSprite("itemicon",itemData.Icon) self.main:FindChild("Name"):GetComponent("UnityEngine.UI.Text").text = itemData.Name end function BountyMatchGetRewardAPI:ClosePanel() Object.Destroy(self.this.transform.gameObject) if CoinMatchAPI~=nil and CoinMatchAPI.Instance~=nil then CoinMatchAPI.Instance:ClosePanel() end end function BountyMatchGetRewardAPI:SetFxOk(model) local btn = model.transform:GetComponentsInChildren(NTGLuaScript.GetType("UnityEngine.Renderer")) for k = 0,btn.Length - 1 do model.transform:GetComponentsInChildren(NTGLuaScript.GetType("UnityEngine.Renderer"))[k].material.shader = UnityEngine.Shader.Find(btn[k].material.shader.name) end end function BountyMatchGetRewardAPI:OnDestroy() self.this = nil BountyMatchGetRewardAPI.Instance = nil self = nil end
0
0.63691
1
0.63691
game-dev
MEDIA
0.958954
game-dev
0.842043
1
0.842043
GregTech6/gregtech6
6,087
src/main/java/gregtech/loaders/b/Loader_Late_Items_And_Blocks.java
/** * Copyright (c) 2025 GregTech-6 Team * * This file is part of GregTech. * * GregTech is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GregTech 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GregTech. If not, see <http://www.gnu.org/licenses/>. */ package gregtech.loaders.b; import gregapi.block.behaviors.Drops; import gregapi.block.behaviors.Drops_SmallOre; import gregapi.block.prefixblock.PrefixBlock; import gregapi.block.prefixblock.PrefixBlock_; import gregapi.code.ItemStackContainer; import gregapi.data.MD; import gregapi.data.MT; import gregapi.data.OP; import gregapi.oredict.OreDictMaterial; import gregapi.render.BlockTextureCopied; import gregapi.util.ST; import gregtech.loaders.a.Loader_Ores; import net.minecraft.block.Block; import static gregapi.data.CS.*; public class Loader_Late_Items_And_Blocks implements Runnable { @Override public void run() { // Atum violates the "Blocks have to be created in preInit" Rule... if (MD.ATUM.mLoaded) { OUT.println("GT_Mod: Register Late Bullshit for Atum."); Block tAtumStone = ST.block(MD.ATUM, "tile.stone"), tAtumCobble = ST.block(MD.ATUM, "tile.cobble"), tAtumSand = ST.block(MD.ATUM, "tile.sand"); if (tAtumCobble != NB && tAtumStone != NB) { BlocksGT.oreAtumLimestone = new PrefixBlock_(MD.GT, "gt.meta.ore.normal.atum" , OP.oreLimestone , null, null, null , BlockTextureCopied.get(tAtumStone , 6, 0) , tAtumStone.getMaterial() , tAtumStone.stepSound , TOOL_pickaxe , 2.0F, 2.0F, 0, 0, 999, 0, 0, 0, 1, 1, 1, F,F,F,F,T,T,F,F,T,T,T,T,T,F, OreDictMaterial.MATERIAL_ARRAY); BlocksGT.oreBrokenAtumLimestone = new PrefixBlock_(MD.GT, "gt.meta.ore.broken.atum" , OP.oreLimestone , null, null, null , BlockTextureCopied.get(tAtumCobble, 6, 0) , tAtumCobble.getMaterial() , tAtumCobble.stepSound , TOOL_pickaxe , 1.0F, 1.0F, -1, 0, 999, 0, 0, 0, 1, 1, 1, T,F,F,F,T,T,F,F,T,T,T,T,T,F, OreDictMaterial.MATERIAL_ARRAY); BlocksGT.oreSmallAtumLimestone = new PrefixBlock_(MD.GT, "gt.meta.ore.small.atum" , OP.oreSmall , null, null, new Drops_SmallOre(MT.STONES.Limestone), BlockTextureCopied.get(tAtumStone , 6, 0) , tAtumStone.getMaterial() , tAtumStone.stepSound , TOOL_pickaxe , 2.0F, 2.0F, -1, 0, 999, 0, 0, 0, 1, 1, 1, F,F,F,F,T,T,F,F,T,T,T,T,T,F, OreDictMaterial.MATERIAL_ARRAY); ((PrefixBlock)BlocksGT.oreAtumLimestone).mDrops = new Drops(BlocksGT.oreBrokenAtumLimestone, BlocksGT.oreAtumLimestone, OP.oreRaw.mRegisteredPrefixItems.get(0), 0, 1); for (byte i = 0; i < 16; i++) { BlocksGT.stoneToBrokenOres.put(new ItemStackContainer(tAtumStone, 1, i), BlocksGT.oreBrokenAtumLimestone); BlocksGT.stoneToNormalOres.put(new ItemStackContainer(tAtumStone, 1, i), BlocksGT.oreAtumLimestone); BlocksGT.stoneToSmallOres .put(new ItemStackContainer(tAtumStone, 1, i), BlocksGT.oreSmallAtumLimestone); } for (int i = 0; i < 10; i++) { ItemsGT.ILLEGAL_DROPS.add((Block)BlocksGT.oreBrokenAtumLimestone, i); ItemsGT.ILLEGAL_DROPS.add((Block)BlocksGT.oreAtumLimestone, i); ItemsGT.ILLEGAL_DROPS.add((Block)BlocksGT.oreSmallAtumLimestone, i); GarbageGT.BLACKLIST.add((Block)BlocksGT.oreBrokenAtumLimestone, i); GarbageGT.BLACKLIST.add((Block)BlocksGT.oreAtumLimestone, i); GarbageGT.BLACKLIST.add((Block)BlocksGT.oreSmallAtumLimestone, i); } } if (tAtumSand != NB) { BlocksGT.oreAtumSand = new PrefixBlock_(MD.GT, "gt.meta.ore.normal.sand.atum" , OP.oreStrangesand , null, null, null , BlockTextureCopied.get(tAtumSand , 6, 0) , tAtumSand.getMaterial() , tAtumSand.stepSound , TOOL_shovel , 2.0F, 2.0F, 0, 0, 999, 0, 0, 0, 1, 1, 1, F,F,F,F,T,T,F,F,T,T,T,T,T,F, OreDictMaterial.MATERIAL_ARRAY); BlocksGT.oreSmallAtumSand = new PrefixBlock_(MD.GT, "gt.meta.ore.small.sand.atum" , OP.oreSmall , null, null, new Drops_SmallOre(MT.STONES.Limestone), BlockTextureCopied.get(tAtumSand , 6, 0) , tAtumSand.getMaterial() , tAtumSand.stepSound , TOOL_shovel , 2.0F, 2.0F, -1, 0, 999, 0, 0, 0, 1, 1, 1, F,F,F,F,T,T,F,F,T,T,T,T,T,F, OreDictMaterial.MATERIAL_ARRAY); for (byte i = 0; i < 16; i++) { BlocksGT.stoneToNormalOres.put(new ItemStackContainer(tAtumSand, 1, i), BlocksGT.oreAtumSand); BlocksGT.stoneToBrokenOres.put(new ItemStackContainer(tAtumSand, 1, i), BlocksGT.oreAtumSand); BlocksGT.stoneToSmallOres .put(new ItemStackContainer(tAtumSand, 1, i), BlocksGT.oreSmallAtumSand); } for (int i = 0; i < 10; i++) { ItemsGT.ILLEGAL_DROPS.add((Block)BlocksGT.oreAtumSand, i); ItemsGT.ILLEGAL_DROPS.add((Block)BlocksGT.oreSmallAtumSand, i); GarbageGT.BLACKLIST.add((Block)BlocksGT.oreAtumSand, i); GarbageGT.BLACKLIST.add((Block)BlocksGT.oreSmallAtumSand, i); } } } if (MD.AETHEL.mLoaded) { Loader_Ores.rockset(MD.AETHEL, "holystone", 1, 0, "holystone", 1, "aether.holystone", OP.oreHolystone, MT.STONES.Holystone); } Loader_Ores.rockset(MD.PR_EXPLORATION, "projectred.exploration.stone", 3, 3, "projectred.exploration.stone", 2, "pr.basalt", OP.oreBasalt, MT.STONES.Basalt); Loader_Ores.rockset(MD.PR_EXPLORATION, "projectred.exploration.stone" , 0, "pr.marble", OP.oreMarble, MT.STONES.Marble); Loader_Ores.rockset(MD.BP, "basalt", 0, 0, "basalt_cobble", 0, "bp.basalt", OP.oreBasalt, MT.STONES.Basalt); Loader_Ores.rockset(MD.BP, "marble" , 0, "bp.marble", OP.oreMarble, MT.STONES.Marble); } }
0
0.888648
1
0.888648
game-dev
MEDIA
0.970964
game-dev
0.927724
1
0.927724
edpsw/exbody2
9,044
legged_gym/resources/robots/g1/g1_joint_index_dds.md
# 电机顺序 ## G1 全身关节电机顺序 `unitree_hg::msg::dds_::LowCmd_.motor_cmd` 与 `unitree_hg::msg::dds_::LowState_.motor_state` 包含 G1 全身电机(不含手)的信息,其电机顺序如下: ### 23DOF 版本 | Joint Index in IDL | Joint Name (LowCmd_.mode or LowState_.mode == 0) | Joint Name (LowCmd_.mode or LowState_.mode == 1) | | ------------------ | ------------------------------------------------ | ------------------------------------------------ | | 0 | L_LEG_HIP_PITCH | L_LEG_HIP_PITCH | | 1 | L_LEG_HIP_ROLL | L_LEG_HIP_ROLL | | 2 | L_LEG_HIP_YAW | L_LEG_HIP_YAW | | 3 | L_LEG_KNEE | L_LEG_KNEE | | 4 | **L_LEG_ANKLE_PITCH** | **L_LEG_ANKLE_B** | | 5 | **L_LEG_ANKLE_ROLL** | **L_LEG_ANKLE_A** | | 6 | R_LEG_HIP_PITCH | R_LEG_HIP_PITCH | | 7 | R_LEG_HIP_ROLL | R_LEG_HIP_ROLL | | 8 | R_LEG_HIP_YAW | R_LEG_HIP_YAW | | 9 | R_LEG_KNEE | R_LEG_KNEE | | 10 | **R_LEG_ANKLE_PITCH** | **R_LEG_ANKLE_B** | | 11 | **R_LEG_ANKLE_ROLL** | **R_LEG_ANKLE_A** | | 12 | TORSO | TORSO | | 13 | L_SHOULDER_PITCH | L_SHOULDER_PITCH | | 14 | L_SHOULDER_ROLL | L_SHOULDER_ROLL | | 15 | L_SHOULDER_YAW | L_SHOULDER_YAW | | 16 | L_ELBOW_PITCH | L_ELBOW_PITCH | | 17 | L_ELBOW_ROLL | L_ELBOW_ROLL | | 18 | R_SHOULDER_PITCH | R_SHOULDER_PITCH | | 19 | R_SHOULDER_ROLL | R_SHOULDER_ROLL | | 20 | R_SHOULDER_YAW | R_SHOULDER_YAW | | 21 | R_ELBOW_PITCH | R_ELBOW_PITCH | | 22 | R_ELBOW_ROLL | R_ELBOW_ROLL | ### 29DOF 版本 | Joint Index in IDL | Joint Name (LowCmd_.mode or LowState_.mode == 0) | Joint Name (LowCmd_.mode or LowState_.mode == 1) | | ------------------ | ------------------------------------------------ | ------------------------------------------------ | | 0 | L_LEG_HIP_PITCH | L_LEG_HIP_PITCH | | 1 | L_LEG_HIP_ROLL | L_LEG_HIP_ROLL | | 2 | L_LEG_HIP_YAW | L_LEG_HIP_YAW | | 3 | L_LEG_KNEE | L_LEG_KNEE | | 4 | **L_LEG_ANKLE_PITCH** | **L_LEG_ANKLE_B** | | 5 | **L_LEG_ANKLE_ROLL** | **L_LEG_ANKLE_A** | | 6 | R_LEG_HIP_PITCH | R_LEG_HIP_PITCH | | 7 | R_LEG_HIP_ROLL | R_LEG_HIP_ROLL | | 8 | R_LEG_HIP_YAW | R_LEG_HIP_YAW | | 9 | R_LEG_KNEE | R_LEG_KNEE | | 10 | **R_LEG_ANKLE_PITCH** | **R_LEG_ANKLE_B** | | 11 | **R_LEG_ANKLE_ROLL** | **R_LEG_ANKLE_A** | | 12 | WAIST_YAW | WAIST_YAW | | 13 | **WAIST_ROLL** | **WAIST_A** | | 14 | **WAIST_PITCH** | **WAIST_B** | | 15 | L_SHOULDER_PITCH | L_SHOULDER_PITCH | | 16 | L_SHOULDER_ROLL | L_SHOULDER_ROLL | | 17 | L_SHOULDER_YAW | L_SHOULDER_YAW | | 18 | L_ELBOW | L_ELBOW | | 19 | L_WRIST_ROLL | L_WRIST_ROLL | | 20 | L_WRIST_PITCH | L_WRIST_PITCH | | 21 | L_WRIST_YAW | L_WRIST_YAW | | 22 | R_SHOULDER_PITCH | R_SHOULDER_PITCH | | 23 | R_SHOULDER_ROLL | R_SHOULDER_ROLL | | 24 | R_SHOULDER_YAW | R_SHOULDER_YAW | | 25 | R_ELBOW | R_ELBOW | | 26 | R_WRIST_ROLL | R_WRIST_ROLL | | 27 | R_WRIST_PITCH | R_WRIST_PITCH | | 28 | R_WRIST_YAW | R_WRIST_YAW | ### 14DOF 双臂版本 | Joint Index in IDL | Joint Name | | ------------------ | ---------------- | | 0 | (empty) | | 1 | (empty) | | 2 | (empty) | | 3 | (empty) | | 4 | (empty) | | 5 | (empty) | | 6 | (empty) | | 7 | (empty) | | 8 | (empty) | | 9 | (empty) | | 10 | (empty) | | 11 | (empty) | | 12 | (empty) | | 13 | (empty) | | 14 | (empty) | | 15 | L_SHOULDER_PITCH | | 16 | L_SHOULDER_ROLL | | 17 | L_SHOULDER_YAW | | 18 | L_ELBOW | | 19 | L_WRIST_ROLL | | 20 | L_WRIST_PITCH | | 21 | L_WRIST_YAW | | 22 | R_SHOULDER_PITCH | | 23 | R_SHOULDER_ROLL | | 24 | R_SHOULDER_YAW | | 25 | R_ELBOW | | 26 | R_WRIST_ROLL | | 27 | R_WRIST_PITCH | | 28 | R_WRIST_YAW | ## Dex3-1 关节电机顺序 `unitree_hg::msg::dds_::HandCmd_.motor_cmd` 与 `unitree_hg::msg::dds_::HandState_.motor_state` 包含所有的灵巧手电机的信息,其电机顺序如下: | Hand Joint Index in IDL | Hand Joint Name | | ----------------------- | --------------- | | 0 | thumb_0 | | 1 | thumb_1 | | 2 | thumb_2 | | 3 | index_0 | | 4 | index_1 | | 5 | middle_0 | | 6 | middle_1 |
0
0.687934
1
0.687934
game-dev
MEDIA
0.200832
game-dev
0.546724
1
0.546724
Ayfri/Kore
1,144
kore/src/main/kotlin/io/github/ayfri/kore/features/itemmodifiers/functions/ApplyBonus.kt
package io.github.ayfri.kore.features.itemmodifiers.functions import io.github.ayfri.kore.features.itemmodifiers.ItemModifier import io.github.ayfri.kore.features.itemmodifiers.formulas.Formula import io.github.ayfri.kore.features.predicates.PredicateAsList import io.github.ayfri.kore.generated.arguments.types.EnchantmentArgument import kotlinx.serialization.Serializable /** * Applies a predefined bonus formula to the item stack count based on an enchantment level. * Mirrors vanilla `minecraft:apply_bonus` with formula types such as binomial_with_bonus_count, * uniform_bonus_count, and ore_drops. * * Docs: https://kore.ayfri.com/docs/item-modifiers * See also: https://minecraft.wiki/w/Item_modifier */ @Serializable data class ApplyBonus( override var conditions: PredicateAsList? = null, var enchantment: EnchantmentArgument, var formula: Formula, ) : ItemFunction() /** Add an `apply_bonus` step to this modifier. */ fun ItemModifier.applyBonus(enchantment: EnchantmentArgument, formula: Formula, block: ApplyBonus.() -> Unit = {}) { modifiers += ApplyBonus(enchantment = enchantment, formula = formula).apply(block) }
0
0.812671
1
0.812671
game-dev
MEDIA
0.694971
game-dev
0.71926
1
0.71926
Direwolf20-MC/JustDireThings
5,500
src/main/java/com/direwolf20/justdirethings/client/screens/ClickerT2Screen.java
package com.direwolf20.justdirethings.client.screens; import com.direwolf20.justdirethings.client.screens.basescreens.BaseMachineScreen; import com.direwolf20.justdirethings.client.screens.standardbuttons.ToggleButtonFactory; import com.direwolf20.justdirethings.client.screens.widgets.GrayscaleButton; import com.direwolf20.justdirethings.client.screens.widgets.NumberButton; import com.direwolf20.justdirethings.client.screens.widgets.ToggleButton; import com.direwolf20.justdirethings.common.blockentities.ClickerT2BE; import com.direwolf20.justdirethings.common.containers.ClickerT2Container; import com.direwolf20.justdirethings.common.network.data.ClickerPayload; import com.direwolf20.justdirethings.common.network.data.DirectionSettingPayload; import com.direwolf20.justdirethings.common.network.data.TickSpeedPayload; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; import net.neoforged.neoforge.network.PacketDistributor; public class ClickerT2Screen extends BaseMachineScreen<ClickerT2Container> { public int clickType; public int clickTarget; public boolean sneaking; public boolean showFakePlayer; public int maxHoldTicks; public NumberButton maxHoldTicksButton; public NumberButton tickSpeedButton; public ClickerT2Screen(ClickerT2Container container, Inventory inv, Component name) { super(container, inv, name); if (baseMachineBE instanceof ClickerT2BE clicker) { clickType = clicker.clickType; clickTarget = clicker.clickTarget.ordinal(); sneaking = clicker.sneaking; showFakePlayer = clicker.showFakePlayer; maxHoldTicks = clicker.maxHoldTicks; } } public void showHoldClicksButton() { if (clickType == 2) widgetsToAdd.add(maxHoldTicksButton); else widgetsToRemove.add(maxHoldTicksButton); renderablesChanged = true; } @Override public void addTickSpeedButton() { if (tickSpeedButton != null && renderables.contains(tickSpeedButton)) widgetsToRemove.add(tickSpeedButton); if (clickType == 2) { tickSpeedButton = ToggleButtonFactory.TICKSPEEDBUTTON(getGuiLeft() + 144, topSectionTop + 40, tickSpeed, maxHoldTicks + 1, b -> { tickSpeed = ((NumberButton) b).getValue(); //The value is updated in the mouseClicked method below PacketDistributor.sendToServer(new TickSpeedPayload(tickSpeed)); }); } else { tickSpeedButton = ToggleButtonFactory.TICKSPEEDBUTTON(getGuiLeft() + 144, topSectionTop + 40, tickSpeed, b -> { tickSpeed = ((NumberButton) b).getValue(); //The value is updated in the mouseClicked method below PacketDistributor.sendToServer(new TickSpeedPayload(tickSpeed)); }); } widgetsToAdd.add(tickSpeedButton); renderablesChanged = true; } @Override public void init() { super.init(); addRenderableWidget(ToggleButtonFactory.DIRECTIONBUTTON(getGuiLeft() + 116, topSectionTop + 62, direction, b -> { direction = ((ToggleButton) b).getTexturePosition(); PacketDistributor.sendToServer(new DirectionSettingPayload(direction)); })); addRenderableWidget(ToggleButtonFactory.CLICKTARGETBUTTON(getGuiLeft() + 44, topSectionTop + 62, clickTarget, b -> { clickTarget = ((ToggleButton) b).getTexturePosition(); saveSettings(); })); addRenderableWidget(ToggleButtonFactory.LEFTRIGHTCLICKBUTTON(getGuiLeft() + 44, topSectionTop + 44, clickType, b -> { clickType = ((ToggleButton) b).getTexturePosition(); if (clickType == 2) { tickSpeed = Math.max(tickSpeed, maxHoldTicks + 1); PacketDistributor.sendToServer(new TickSpeedPayload(tickSpeed)); } addTickSpeedButton(); saveSettings(); showHoldClicksButton(); })); maxHoldTicksButton = new NumberButton(getGuiLeft() + 64, topSectionTop + 46, 24, 12, maxHoldTicks, 1, 1200, Component.translatable("justdirethings.screen.click-hold-for"), b -> { maxHoldTicks = ((NumberButton) b).getValue(); //The value is updated in the mouseClicked method below if (clickType == 2) { tickSpeed = Math.max(tickSpeed, maxHoldTicks + 1); PacketDistributor.sendToServer(new TickSpeedPayload(tickSpeed)); } addTickSpeedButton(); saveSettings(); }); showHoldClicksButton(); addRenderableWidget(ToggleButtonFactory.SNEAKCLICKBUTTON(getGuiLeft() + 26, topSectionTop + 44, sneaking, b -> { sneaking = !sneaking; ((GrayscaleButton) b).toggleActive(); saveSettings(); })); addRenderableWidget(ToggleButtonFactory.SHOWFAKEPLAYERBUTTON(getGuiLeft() + 8, topSectionTop + 44, showFakePlayer, b -> { showFakePlayer = !showFakePlayer; ((GrayscaleButton) b).toggleActive(); saveSettings(); })); } @Override public void setTopSection() { extraWidth = 60; extraHeight = 0; } @Override public void saveSettings() { super.saveSettings(); PacketDistributor.sendToServer(new ClickerPayload(clickType, clickTarget, sneaking, showFakePlayer, maxHoldTicks)); } }
0
0.748027
1
0.748027
game-dev
MEDIA
0.904022
game-dev
0.950157
1
0.950157
ggnkua/Atari_ST_Sources
12,150
C/Christophe Fontanel/ReDMCSB_Release2/OBJECT/ENGINE/FULL/DM11EN/TEXT.S
BSS SEG "bss" G353_ac_St:/* global */ .WORD #128 CODE SEG "init!" MOVE #-1,G354_i_Mes(A4) BSS SEG "bss" G354_i_Mes:/* global */ .WORD #2 G355_B_Scr:/* global */ .WORD #2 G356_puc_B:/* global */ .WORD #4 G357_puc_I:/* global */ .WORD #4 G358_i_Mes:/* global */ .WORD #2 G359_i_Mes:/* global */ .WORD #2 G360_al_Me:/* global */ .WORD #16 CODE SEG "main" F040_aacZ_:/* global */ LINK A6,L$0 MOVEM.L A3-A2/D7-D4,-(A7) MOVE.L 8(A6),A3 MOVE 14(A6),D7 MOVE 16(A6),D6 MOVE 18(A6),D5 MOVE 20(A6),D4 MOVE.L 22(A6),A0 MOVE.B (A0),D0 BNE.S L0T040_001 BRA L0T040_043_(PC) L0T040_001: MOVE D6,D0 SUBQ #4,D0 MULU 12(A6),D0 ADDA D0,A3 MOVE D7,D0 ANDI #-16,D0 LSR #1,D0 ADDA D0,A3 MOVEQ #15,D3 AND D7,D3 MOVE D5,D1 ADD D5,D5 ADD D1,D5 ADD D5,D5 JMP 2(PC,D5) L0T040_002: LEA L0T040_025_(PC),A0 BRA.S L0T040_003_ LEA L0T040_010_(PC),A0 BRA.S L0T040_003_ LEA L0T040_011_(PC),A0 BRA.S L0T040_003_ LEA L0T040_012_(PC),A0 BRA.S L0T040_003_ LEA L0T040_013_(PC),A0 BRA.S L0T040_003_ LEA L0T040_014_(PC),A0 BRA.S L0T040_003_ LEA L0T040_015_(PC),A0 BRA.S L0T040_003_ LEA L0T040_016_(PC),A0 BRA.S L0T040_003_ LEA L0T040_017_(PC),A0 BRA.S L0T040_003_ LEA L0T040_018_(PC),A0 BRA.S L0T040_003_ LEA L0T040_019_(PC),A0 BRA.S L0T040_003_ LEA L0T040_020_(PC),A0 BRA.S L0T040_003_ LEA L0T040_021_(PC),A0 BRA.S L0T040_003_ LEA L0T040_022_(PC),A0 BRA.S L0T040_003_ LEA L0T040_023_(PC),A0 BRA.S L0T040_003_ LEA L0T040_024_(PC),A0 L0T040_003_: MOVE D4,D1 ADD D4,D4 ADD D1,D4 ADD D4,D4 JMP 2(PC,D4) L0T040_004_: LEA L0T040_041_(PC),A1 BRA.S L0T040_005_ LEA L0T040_026_(PC),A1 BRA.S L0T040_005_ LEA L0T040_027_(PC),A1 BRA.S L0T040_005_ LEA L0T040_028_(PC),A1 BRA.S L0T040_005_ LEA L0T040_029_(PC),A1 BRA.S L0T040_005_ LEA L0T040_030_(PC),A1 BRA.S L0T040_005_ LEA L0T040_031_(PC),A1 BRA.S L0T040_005_ LEA L0T040_032_(PC),A1 BRA.S L0T040_005_ LEA L0T040_033_(PC),A1 BRA.S L0T040_005_ LEA L0T040_034_(PC),A1 BRA.S L0T040_005_ LEA L0T040_035_(PC),A1 BRA.S L0T040_005_ LEA L0T040_036_(PC),A1 BRA.S L0T040_005_ LEA L0T040_037_(PC),A1 BRA.S L0T040_005_ LEA L0T040_038_(PC),A1 BRA.S L0T040_005_ LEA L0T040_039_(PC),A1 BRA.S L0T040_005_ LEA L0T040_040_(PC),A1 L0T040_005_: MOVEQ #0,D2 MOVE.L 22(A6),A2 MOVE.B (A2),D2 BEQ L0T040_043_(PC) ADDQ.L #1,22(A6) MOVE.L G357_puc_I(A4),A2 LEA 0(A2,D2),A2 CMP #11,D3 BHI.S L0T040_006_ MOVEQ #6,D4 MOVE.L #134154239,D2 ROR.L D3,D2 MOVEQ #0,D5 MOVE.L A3,-(A7) BSR.S L0T040_007_ MOVE.L (A7)+,A3 ADDQ #6,D3 CMPI #16,D3 BCS.S L0T040_005_ ANDI #1,D3 ADDQ.L #8,A3 BRA.S L0T040_005_ L0T040_006_: MOVEQ #6,D4 MOVE.L A3,-(A7) ADDQ.L #8,(A7) MOVE.L A2,-(A7) LSL #2,D3 LEA G064_al_Gr+-48(A4),A2 MOVE.L 0(A2,D3),D2 LEA G065_al_Gr+-48(A4),A2 MOVE.L 0(A2,D3),-(A7) LSR #2,D3 MOVE.L 4(A7),A2 MOVEQ #8,D5 BSR.S L0T040_007_ MOVE.L (A7)+,D2 MOVE.L (A7)+,A2 MOVE.L (A7),A3 MOVEQ #6,D4 MOVEQ #18,D5 BSR.S L0T040_007_ MOVE.L (A7)+,A3 SUBI #10,D3 BRA.S L0T040_005_ L0T040_007_: AND.L D2,(A3) AND.L D2,4(A3) MOVEQ #0,D0 MOVE.B (A2),D0 JMP 2(PC,D5) L0T040_008: MOVEQ #11,D1 SUB D3,D1 LSL D1,D0 BRA.S L0T040_009 MOVE D3,D1 SUBI #11,D1 LSR D1,D0 BRA.S L0T040_009 MOVEQ #27,D1 SUB D3,D1 LSL D1,D0 L0T040_009: MOVE D0,D1 SWAP D1 MOVE D0,D1 SWAP D0 MOVEQ #0,D6 MOVEQ #0,D7 JMP (A0) L0T040_010_: MOVE.L D0,D6 BRA.S L0T040_025_ L0T040_011_: MOVE D1,D6 BRA.S L0T040_025_ L0T040_012_: MOVE.L D1,D6 BRA.S L0T040_025_ L0T040_013_: MOVE.L D0,D7 BRA.S L0T040_025_ L0T040_014_: MOVE.L D0,D6 MOVE.L D0,D7 BRA.S L0T040_025_ L0T040_015_: MOVE D1,D6 MOVE.L D0,D7 BRA.S L0T040_025_ L0T040_016_: MOVE.L D1,D6 MOVE.L D0,D7 BRA.S L0T040_025_ L0T040_017_: MOVE D1,D7 BRA.S L0T040_025_ L0T040_018_: MOVE.L D0,D6 MOVE D1,D7 BRA.S L0T040_025_ L0T040_019_: MOVE D1,D6 MOVE D1,D7 BRA.S L0T040_025_ L0T040_020_: MOVE.L D1,D6 MOVE D1,D7 BRA.S L0T040_025_ L0T040_021_: MOVE.L D1,D7 BRA.S L0T040_025_ L0T040_022_: MOVE.L D0,D6 MOVE.L D1,D7 BRA.S L0T040_025_ L0T040_023_: MOVE D1,D6 MOVE.L D1,D7 BRA.S L0T040_025_ L0T040_024_: MOVE.L D1,D6 MOVE.L D1,D7 L0T040_025_: OR.L D2,D0 NOT.L D0 CLR D0 OR.L D2,D1 NOT.L D1 JMP (A1) L0T040_026_: OR.L D0,D6 BRA.S L0T040_041_ L0T040_027_: OR D1,D6 BRA.S L0T040_041_ L0T040_028_: OR.L D1,D6 BRA.S L0T040_041_ L0T040_029_: OR.L D0,D7 BRA.S L0T040_041_ L0T040_030_: OR.L D0,D6 OR.L D0,D7 BRA.S L0T040_041_ L0T040_031_: OR D1,D6 OR.L D0,D7 BRA.S L0T040_041_ L0T040_032_: OR.L D1,D6 OR.L D0,D7 BRA.S L0T040_041_ L0T040_033_: OR D1,D7 BRA.S L0T040_041_ L0T040_034_: OR.L D0,D6 OR D1,D7 BRA.S L0T040_041_ L0T040_035_: OR D1,D6 OR D1,D7 BRA.S L0T040_041_ L0T040_036_: OR.L D1,D6 OR D1,D7 BRA.S L0T040_041_ L0T040_037_: OR.L D1,D7 BRA.S L0T040_041_ L0T040_038_: OR.L D0,D6 OR.L D1,D7 BRA.S L0T040_041_ L0T040_039_: OR D1,D6 OR.L D1,D7 BRA.S L0T040_041_ L0T040_040_: OR.L D1,D6 OR.L D1,D7 L0T040_041_: OR.L D6,(A3) OR.L D7,4(A3) SUBQ #1,D4 BNE.S L0T040_042 RTS L0T040_042: LEA 128(A2),A2 ADDA 12(A6),A3 BRA L0T040_007_(PC) L0T040_043_: MOVEM.L (A7)+,D4-D7/A2-A3 L1: UNLK A6 RTS L$0: .EQU #0 F041_aadZ_:/* global */ LINK A6,L$2 MOVEM.L A3/D7,-(A7) MOVE.L 22(A6),A3 CLR D7 BRA.S L4 L5: ADDQ #1,D7 L4: LEA -80(A6),A0 ADDA D7,A0 MOVE.B (A3)+,(A0) BNE.S L5 L6: BRA.S L7 L8: LEA -80(A6),A0 ADDA D7,A0 MOVE.B #32,(A0) ADDQ #1,D7 L7: MOVE D7,D0 CMP 26(A6),D0 BLT.S L8 L9: LEA -80(A6),A0 ADDA D7,A0 CLR.B (A0) PEA -80(A6) MOVE 20(A6),-(A7) MOVE 18(A6),-(A7) MOVE 16(A6),-(A7) MOVE 14(A6),-(A7) MOVE 12(A6),-(A7) MOVE.L 8(A6),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 L3: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$2: .EQU #-80 F042_xxxx_:/* global */ LINK A6,L$10 MOVEM.L D7-D6,-(A7) MOVE 8(A6),D7 MOVE 10(A6),D6 CMPI #0,D7 BGE.S L12 CLR D7 BRA.S L13 L12: CMPI #53,D7 BLT.S L14 MOVE #52,D7 L14: L13: MOVE D7,G359_i_Mes(A4) CMPI #0,D6 BGE.S L15 CLR D6 BRA.S L16 L15: CMPI #4,D6 BLT.S L17 MOVE #3,D6 L17: L16: MOVE D6,G358_i_Mes(A4) L11: MOVEM.L (A7)+,D6-D7 UNLK A6 RTS L$10: .EQU #0 F043_aahz_:/* global */ LINK A6,L$18 MOVE D7,-(A7) CLR G578_B_Use(A4) CLR -8(A6) MOVE #319,-6(A6) MOVE #169,-4(A6) MOVE #199,-2(A6) L21: L20: CMPI #0,G354_i_Mes(A4) BGE.S L21 MOVE G355_B_Scr(A4),D0 BNE.S L21 L22: JSR F077_aA39_(PC) MOVE #160,-(A7) CLR -(A7) PEA -8(A6) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 JSR F078_xzzz_(PC) MOVE #3,G358_i_Mes(A4) CLR G359_i_Mes(A4) CLR D7 BRA.S L23 L24: MOVE D7,D0 ASL.L #2,D0 LEA G360_al_Me(A4),A0 ADDA D0,A0 MOVE.L #-1,(A0) L25: ADDQ #1,D7 L23: CMPI #4,D7 BCS.S L24 L26: L19: MOVE (A7)+,D7 UNLK A6 RTS L$18: .EQU #-8 F044_xxxx_:/* global */ LINK A6,L$27 MOVEM.L D7-D5,-(A7) CLR G578_B_Use(A4) CLR -8(A6) MOVE #319,-6(A6) CLR D6 BRA.S L29 L30: MOVE D6,D5 ASL.L #2,D5 LEA G360_al_Me(A4),A0 ADDA D5,A0 MOVE.L (A0),D5 CMPI.L #-1,D5 BEQ.S L34 MOVE.L D5,D0 MOVE.L G313_ul_Ga(A4),D1 CMP.L D1,D0 BLE.S L33 L34: BRA.S L31 L33: MOVE #172,D0 MOVE D6,D1 MULU #7,D1 ADD D1,D0 MOVE D0,-4(A6) ADDQ #6,D0 MOVE D0,-2(A6) L36: L35: CMPI #0,G354_i_Mes(A4) BGE.S L36 MOVE G355_B_Scr(A4),D0 BNE.S L36 L37: JSR F077_aA39_(PC) MOVE #160,-(A7) CLR -(A7) PEA -8(A6) MOVE.L G348_pl_Bi(A4),-(A7) JSR F135_xzzz_(PC) ADDA #12,A7 JSR F078_xzzz_(PC) MOVE D6,D0 ASL.L #2,D0 LEA G360_al_Me(A4),A0 ADDA D0,A0 MOVE.L #-1,(A0) L31: ADDQ #1,D6 L29: CMPI #4,D6 BCS.S L30 L32: L28: MOVEM.L (A7)+,D5-D7 UNLK A6 RTS L$27: .EQU #-8 F045_xxxx_:/* global */ LINK A6,L$38 MOVE D7,-(A7) CMPI #3,G358_i_Mes(A4) BNE.S L40 L42: L41: CMPI #0,G354_i_Mes(A4) BGE.S L42 MOVE G355_B_Scr(A4),D0 BNE.S L42 L43: MOVE #1120,-(A7) MOVE.L G356_puc_B(A4),-(A7) JSR F008_aA19_(PC) ADDQ.L #6,A7 CLR G354_i_Mes(A4) CLR D7 BRA.S L44 L45: MOVE D7,D0 ASL.L #2,D0 LEA G360_al_Me+4(A4),A0 ADDA D0,A0 MOVE.L (A0),D0 MOVE D7,D1 ASL.L #2,D1 LEA G360_al_Me(A4),A0 ADDA D1,A0 MOVE.L D0,(A0) L46: ADDQ #1,D7 L44: CMPI #3,D7 BCS.S L45 L47: MOVE.L #-1,G360_al_Me+12(A4) BRA.S L48 L40: ADDQ #1,G358_i_Mes(A4) L48: L39: MOVE (A7)+,D7 UNLK A6 RTS L$38: .EQU #0 F046_xxxx_:/* global */ LINK A6,L$49 MOVEM.L A3/D7,-(A7) MOVE.L 10(A6),A3 MOVE.L A3,-(A7) JSR strlen(PC) ADDQ.L #4,A7 MOVE D0,D7 CMPI #-1,G354_i_Mes(A4) BNE.S L51 L53: L52: MOVE G355_B_Scr(A4),D0 BNE.S L53 L54: JSR F077_aA39_(PC) MOVE.L A3,-(A7) CLR -(A7) MOVE 8(A6),-(A7) MOVE G358_i_Mes(A4),D0 MULS #7,D0 ADD #177,D0 MOVE D0,-(A7) MOVE G359_i_Mes(A4),D0 MULS #6,D0 MOVE D0,-(A7) JSR F053_aajz_(PC) ADDA #12,A7 JSR F078_xzzz_(PC) BRA.S L55 L51: MOVE.L A3,-(A7) CLR -(A7) MOVE 8(A6),-(A7) MOVE #5,-(A7) MOVE G359_i_Mes(A4),D0 MULS #6,D0 MOVE D0,-(A7) MOVE #160,-(A7) MOVE.L G356_puc_B(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 CMPI #-1,G354_i_Mes(A4) BNE.S L56 MOVE #1,G355_B_Scr(A4) L56: L55: MOVE D7,D0 ADD D0,G359_i_Mes(A4) MOVE.L G313_ul_Ga(A4),D0 ADD.L #70,D0 MOVE G358_i_Mes(A4),D1 ASL.L #2,D1 LEA G360_al_Me(A4),A0 ADDA D1,A0 MOVE.L D0,(A0) L50: MOVEM.L (A7)+,D7/A3 UNLK A6 RTS L$49: .EQU #0 F047_xzzz_:/* global */ LINK A6,L$57 MOVEM.L A3/D7-D6,-(A7) MOVE 8(A6),D7 MOVE.L 10(A6),A3 BRA L59(PC) L60: MOVE.B (A3),D0 EXT D0 CMP #10,D0 BNE.S L62 ADDQ.L #1,A3 CMPI #0,G359_i_Mes(A4) BNE.S L64 CMPI #0,G358_i_Mes(A4) BEQ.S L63 L64: CLR G359_i_Mes(A4) JSR F045_xxxx_(PC) L63: BRA.S L59 L62: MOVE.B (A3),D0 EXT D0 CMP #32,D0 BNE.S L65 ADDQ.L #1,A3 CMPI #53,G359_i_Mes(A4) BEQ.S L66 MOVE #8192,-2(A6) PEA -2(A6) MOVE D7,-(A7) JSR F046_xxxx_(PC) ADDQ.L #6,A7 L66: BRA.S L59 L65: CLR D6 L67: MOVE D6,D0 ADDQ #1,D6 LEA -56(A6),A0 ADDA D0,A0 MOVE.B (A3)+,(A0) L68: MOVE.B (A3),D0 BEQ.S L70 MOVE.B (A3),D0 EXT D0 CMP #32,D0 BEQ.S L70 MOVE.B (A3),D0 EXT D0 CMP #10,D0 BNE.S L67 L70: L69: MOVE D6,D0 LEA -56(A6),A0 ADDA D0,A0 CLR.B (A0) MOVE G359_i_Mes(A4),D0 ADD D6,D0 CMPI #53,D0 BLS.S L71 MOVE #2,G359_i_Mes(A4) JSR F045_xxxx_(PC) L71: PEA -56(A6) MOVE D7,-(A7) JSR F046_xxxx_(PC) ADDQ.L #6,A7 L59: MOVE.B (A3),D0 BNE L60(PC) L61: L58: MOVEM.L (A7)+,D6-D7/A3 UNLK A6 RTS L$57: .EQU #-56 F048_xxxx_:/* global */ LINK A6,L$72 MOVE.B 11(A6),-2(A6) CLR.B -1(A6) PEA -2(A6) MOVE 8(A6),-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 L73: UNLK A6 RTS L$72: .EQU #-2 F049_xxxx_:/* global */ LINK A6,L$74 MOVEM.L D7-D6,-(A7) MOVE 10(A6),D7 MOVE #7,D6 CLR.B -1(A6) L76: MOVE #48,D0 MOVE D7,D1 AND.L #65535,D1 DIVU #10,D1 SWAP D1 ADD D1,D0 SUBQ #1,D6 MOVE D6,D1 LEA -8(A6),A0 ADDA D1,A0 MOVE.B D0,(A0) L77: MOVE D7,D0 AND.L #65535,D0 DIVU #10,D0 MOVE D0,D7 BNE.S L76 L78: MOVE D6,D0 LEA -8(A6),A0 ADDA D0,A0 LEA (A0),A0 MOVE.L A0,-(A7) MOVE 8(A6),-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 L75: MOVEM.L (A7)+,D6-D7 UNLK A6 RTS L$74: .EQU #-8 F050_xxxx_:/* global */ LINK A6,L$79 DATA SEG "s!" s!: DATA 20 00 CODE SEG "main" PEA s!(A4) MOVE #15,-(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 L80: UNLK A6 RTS L$79: .EQU #0 F051_AA19_:/* global */ LINK A6,L$81 PEA G066_ac_Gr(A4) CLR -(A7) JSR F047_xzzz_(PC) ADDQ.L #6,A7 L82: UNLK A6 RTS L$81: .EQU #0 F052_aaoz_:/* global */ LINK A6,L$83 MOVE.L 14(A6),-(A7) MOVE #12,-(A7) MOVE 12(A6),-(A7) MOVE 10(A6),-(A7) MOVE 8(A6),-(A7) MOVE #112,-(A7) MOVE.L G296_puc_B(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 L84: UNLK A6 RTS L$83: .EQU #0 F053_aajz_:/* global */ LINK A6,L$85 MOVE.L 16(A6),-(A7) MOVE 14(A6),-(A7) MOVE 12(A6),-(A7) MOVE 10(A6),-(A7) MOVE 8(A6),-(A7) MOVE #160,-(A7) MOVE.L G348_pl_Bi(A4),-(A7) JSR F040_aacZ_(PC) ADDA #18,A7 L86: UNLK A6 RTS L$85: .EQU #0 F054_aAA1_:/* global */ LINK A6,L$87 MOVE D7,-(A7) MOVE #3,-(A7) CLR -(A7) JSR F042_xxxx_(PC) ADDQ.L #4,A7 MOVE #1,-(A7) MOVE.L #1120,-(A7) JSR F468_ozzz_(PC) ADDQ.L #6,A7 MOVE.L D0,G356_puc_B(A4) MOVE #1,-(A7) MOVE.L #768,-(A7) JSR F468_ozzz_(PC) ADDQ.L #6,A7 MOVE.L D0,G357_puc_I(A4) MOVE.L G357_puc_I(A4),-(A7) MOVE #-32211,-(A7) JSR F490_lzzz_(PC) ADDQ.L #6,A7 CLR D7 BRA.S L89 L90: MOVE D7,D0 ASL.L #2,D0 LEA G360_al_Me(A4),A0 ADDA D0,A0 MOVE.L #-1,(A0) L91: ADDQ #1,D7 L89: CMPI #4,D7 BCS.S L90 L92: L88: MOVE (A7)+,D7 UNLK A6 RTS L$87: .EQU #0
0
0.752464
1
0.752464
game-dev
MEDIA
0.70615
game-dev
0.902265
1
0.902265
genshinsim/gcsim
1,487
internal/characters/traveler/common/dendro/burst.go
package dendro import ( "github.com/genshinsim/gcsim/internal/frames" "github.com/genshinsim/gcsim/pkg/core/action" ) var burstFrames [][]int const ( burstKey = "travelerdendro-q" burstHitmark = 91 leaLotusAppear = 54 ) func init() { burstFrames = make([][]int, 2) // Male burstFrames[0] = frames.InitAbilSlice(58) burstFrames[0][action.ActionSwap] = 57 // Q -> Swap // Female burstFrames[1] = frames.InitAbilSlice(58) burstFrames[1][action.ActionSwap] = 57 // Q -> Swap } func (c *Traveler) Burst(p map[string]int) (action.Info, error) { c.SetCD(action.ActionBurst, 1200) c.ConsumeEnergy(2) // Duration counts from first hitmark c.Core.Tasks.Add(func() { s := c.newLeaLotusLamp() if c.Base.Ascension >= 1 { // A1 adds a stack per second for delay := 0; delay <= s.Duration; delay += 60 { c.a1Stack(delay) } // A1/C6 buff ticks every 0.3s and applies for 1s. probably counting from gadget spawn - Kolibri for delay := 0; delay <= s.Duration; delay += 0.3 * 60 { c.a1Buff(delay) } } if c.Base.Cons >= 6 { for delay := 0; delay <= s.Duration; delay += 0.3 * 60 { c.c6Buff(delay) } } c.Core.Combat.AddGadget(s) }, leaLotusAppear) return action.Info{ Frames: frames.NewAbilFunc(burstFrames[c.gender]), AnimationLength: burstFrames[c.gender][action.InvalidAction], CanQueueAfter: burstFrames[c.gender][action.ActionSwap], // earliest cancel State: action.BurstState, }, nil }
0
0.865828
1
0.865828
game-dev
MEDIA
0.452969
game-dev
0.944829
1
0.944829
FlameskyDexive/ETPlus
1,362
Unity/Assets/Scripts/Loader/Plugins/Asyncoroutine/AwaiterCoroutineer.cs
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using UnityEngine; namespace ET { public class AwaiterCoroutineer : MonoBehaviour { private static AwaiterCoroutineer _instance; public static AwaiterCoroutineer Instance { get { Install(); return _instance; } } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] public static void Install() { if (_instance == null) _instance = new GameObject("AwaiterCoroutineer").AddComponent<AwaiterCoroutineer>(); } public SynchronizationContext SynchronizationContext { get; private set; } private void Awake() { if (_instance == null) _instance = this; DontDestroyOnLoad(_instance); SynchronizationContext = SynchronizationContext.Current; } public void StartAwaiterCoroutine<T>(AwaiterCoroutine<T> awaiterCoroutine) { StartCoroutine(awaiterCoroutine.Coroutine); } public void StopAwaiterCoroutine<T>(AwaiterCoroutine<T> awaiterCoroutine) { StopCoroutine(awaiterCoroutine.Coroutine); } } }
0
0.806659
1
0.806659
game-dev
MEDIA
0.666624
game-dev
0.856134
1
0.856134
Crypto137/MHServerEmu
3,760
src/MHServerEmu.Games/GameData/GameDataExtensions.cs
using MHServerEmu.Core.Extensions; using MHServerEmu.Games.GameData.Calligraphy; using MHServerEmu.Games.GameData.Prototypes; namespace MHServerEmu.Games.GameData { /// <summary> /// Provides shortcuts for access to game data. /// </summary> public static class GameDataExtensions { /// <summary> /// Returns the <see cref="AssetType"/> that this <see cref="AssetTypeId"/> refers to. /// </summary> public static AssetType AsAssetType(this AssetTypeId assetTypeId) { return GameDatabase.GetAssetType(assetTypeId); } /// <summary> /// Returns the <see cref="Curve"/> that this <see cref="CurveId"/> refers to. /// </summary> public static Curve AsCurve(this CurveId curveId) { return GameDatabase.GetCurve(curveId); } /// <summary> /// Returns the <see cref="Blueprint"/> that this <see cref="BlueprintId"/> refers to. /// </summary> public static Blueprint AsBlueprint(this BlueprintId blueprintId) { return GameDatabase.GetBlueprint(blueprintId); } /// <summary> /// Returns the <typeparamref name="T"/> that this <see cref="PrototypeId"/> refers to. /// </summary> public static T As<T>(this PrototypeId prototypeId) where T: Prototype { return GameDatabase.GetPrototype<T>(prototypeId); } /// <summary> /// Returns the name of this <see cref="AssetTypeId"/>. /// </summary> public static string GetName(this AssetTypeId assetTypeId) { return GameDatabase.GetAssetTypeName(assetTypeId); } /// <summary> /// Returns the name of this <see cref="AssetId"/>. /// </summary> public static string GetName(this AssetId assetId) { return GameDatabase.GetAssetName(assetId); } /// <summary> /// Returns the name of this <see cref="CurveId"/>. /// </summary> public static string GetName(this CurveId curveId) { return GameDatabase.GetCurveName(curveId); } /// <summary> /// Returns the name of this <see cref="BlueprintId"/>. /// </summary> public static string GetName(this BlueprintId blueprintId) { return GameDatabase.GetBlueprintName(blueprintId); } /// <summary> /// Returns the name of this <see cref="PrototypeId"/>. /// </summary> public static string GetName(this PrototypeId prototypeId) { return GameDatabase.GetPrototypeName(prototypeId); } /// <summary> /// Returns the formatted name of this <see cref="PrototypeId"/> (just the file name instead of the whole path). /// </summary> public static string GetNameFormatted(this PrototypeId prototypeId) { return GameDatabase.GetFormattedPrototypeName(prototypeId); } /// <summary> /// Returns <see langword="true"/> if this <see cref="PrototypeId"/> array shares any elements with another one. /// </summary> public static bool ShareElement(this PrototypeId[] protoRefs, PrototypeId[] otherProtoRefs) { if (protoRefs.IsNullOrEmpty() || otherProtoRefs.IsNullOrEmpty()) return false; foreach (PrototypeId protoRef in protoRefs) { foreach (PrototypeId otherProtoRef in otherProtoRefs) { if (protoRef == otherProtoRef) return true; } } return false; } } }
0
0.61728
1
0.61728
game-dev
MEDIA
0.866549
game-dev
0.6133
1
0.6133
oxylusengine/Oxylus
65,367
Oxylus/src/Scene/Scene.cpp
#include "Scene/Scene.hpp" #include <Core/FileSystem.hpp> #include <Jolt/Jolt.h> #include <Jolt/Physics/Body/AllowedDOFs.h> #include <Jolt/Physics/Body/BodyCreationSettings.h> #include <Jolt/Physics/Character/Character.h> #include <Jolt/Physics/Collision/Shape/BoxShape.h> #include <Jolt/Physics/Collision/Shape/CapsuleShape.h> #include <Jolt/Physics/Collision/Shape/CylinderShape.h> #include <Jolt/Physics/Collision/Shape/MeshShape.h> #include <Jolt/Physics/Collision/Shape/MutableCompoundShape.h> #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h> #include <Jolt/Physics/Collision/Shape/SphereShape.h> #include <Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h> #include <glm/gtx/matrix_decompose.hpp> #include <simdjson.h> #include <sol/state.hpp> #include "Asset/AssetManager.hpp" #include "Core/App.hpp" #include "Core/Enum.hpp" #include "Memory/Stack.hpp" #include "Physics/Physics.hpp" #include "Physics/PhysicsInterfaces.hpp" #include "Physics/PhysicsMaterial.hpp" #include "Render/Camera.hpp" #include "Render/RendererConfig.hpp" #include "Render/Utils/VukCommon.hpp" #include "Scene/ECSModule/ComponentWrapper.hpp" #include "Scene/ECSModule/Core.hpp" #include "Scripting/LuaManager.hpp" #include "Utils/JsonHelpers.hpp" #include "Utils/JsonWriter.hpp" #include "Utils/Random.hpp" #include "Utils/Timestep.hpp" namespace ox { auto Scene::safe_entity_name(this const Scene& self, std::string prefix) -> std::string { ZoneScoped; u32 index = 0; std::string new_entity_name = prefix; while (self.world.lookup(new_entity_name.data()) > 0) { index += 1; new_entity_name = fmt::format("{}_{}", prefix, index); } return new_entity_name; } auto Scene::entity_to_json(JsonWriter& writer, flecs::entity e) -> void { ZoneScoped; writer.begin_obj(); writer["name"] = e.name(); std::vector<ECS::ComponentWrapper> components = {}; writer["tags"].begin_array(); e.each([&](flecs::id component_id) { if (!component_id.is_entity()) { return; } ECS::ComponentWrapper component(e, component_id); if (!component.is_component()) { writer << component.path; } else { components.emplace_back(e, component_id); } }); writer.end_array(); writer["components"].begin_array(); for (auto& component : components) { writer.begin_obj(); writer["name"] = component.path; component.for_each([&](usize&, std::string_view member_name, ECS::ComponentWrapper::Member& member) { auto& member_json = writer[member_name]; std::visit( ox::match{ [](const auto&) {}, [&](bool* v) { member_json = *v; }, [&](u16* v) { member_json = *v; }, [&](f32* v) { member_json = *v; }, [&](i32* v) { member_json = *v; }, [&](u32* v) { member_json = *v; }, [&](i64* v) { member_json = *v; }, [&](u64* v) { member_json = *v; }, [&](glm::vec2* v) { member_json = *v; }, [&](glm::vec3* v) { member_json = *v; }, [&](glm::vec4* v) { member_json = *v; }, [&](glm::quat* v) { member_json = *v; }, [&](glm::mat4* v) { member_json = std::span(glm::value_ptr(*v), 16); }, [&](std::string* v) { member_json = *v; }, [&](UUID* v) { member_json = v->str().c_str(); }, }, member ); }); writer.end_obj(); } writer.end_array(); writer["children"].begin_array(); e.children([&writer](flecs::entity c) { entity_to_json(writer, c); }); writer.end_array(); writer.end_obj(); } auto Scene::json_to_entity( Scene& self, flecs::entity root, simdjson::ondemand::value& json, std::vector<UUID>& requested_assets ) -> std::pair<flecs::entity, bool> { ZoneScoped; memory::ScopedStack stack; const auto& world = self.world; auto entity_name_json = json["name"]; if (entity_name_json.error()) { OX_LOG_ERROR("Entities must have names!"); return {{}, false}; } auto e = self.create_entity(std::string(entity_name_json.get_string().value_unsafe())); if (root != flecs::entity::null()) e.child_of(root); auto entity_tags_json = json["tags"]; for (auto entity_tag : entity_tags_json.get_array()) { auto tag = world.component(stack.null_terminate(entity_tag.get_string().value_unsafe()).data()); e.add(tag); } auto components_json = json["components"]; for (auto component_json : components_json.get_array()) { auto component_name_json = component_json["name"]; if (component_name_json.error()) { OX_LOG_ERROR("Entity '{}' has corrupt components JSON array.", e.name().c_str()); return {{}, false}; } const auto* component_name = stack.null_terminate_cstr(component_name_json.get_string().value_unsafe()); auto component_id = world.lookup(component_name); if (!component_id) { OX_LOG_ERROR("Entity '{}' has invalid component named '{}'!", e.name().c_str(), component_name); return {{}, false}; } if (!self.component_db.is_component_known(component_id)) { OX_LOG_WARN("Skipping unkown component {}:{}", component_name, (u64)component_id); continue; } e.add(component_id); ECS::ComponentWrapper component(e, component_id); component.for_each([&](usize&, std::string_view member_name, ECS::ComponentWrapper::Member& member) { auto member_json = component_json[member_name]; if (member_json.error()) { // Default construct return; } std::visit( ox::match{ [](const auto&) {}, [&](bool* v) { *v = static_cast<bool>(member_json.get_bool().value_unsafe()); }, [&](u16* v) { *v = static_cast<u16>(member_json.get_uint64().value_unsafe()); }, [&](f32* v) { *v = static_cast<f32>(member_json.get_double().value_unsafe()); }, [&](i32* v) { *v = static_cast<i32>(member_json.get_int64().value_unsafe()); }, [&](u32* v) { *v = static_cast<u32>(member_json.get_uint64().value_unsafe()); }, [&](i64* v) { *v = member_json.get_int64().value_unsafe(); }, [&](u64* v) { *v = member_json.get_uint64().value_unsafe(); }, [&](glm::vec2* v) { json_to_vec(member_json.value_unsafe(), *v); }, [&](glm::vec3* v) { json_to_vec(member_json.value_unsafe(), *v); }, [&](glm::vec4* v) { json_to_vec(member_json.value_unsafe(), *v); }, [&](glm::quat* v) { json_to_quat(member_json.value_unsafe(), *v); }, // [&](glm::mat4 *v) {json_to_mat(member_json.value(), *v); }, [&](std::string* v) { *v = member_json.get_string().value_unsafe(); }, [&](UUID* v) { *v = UUID::from_string(member_json.get_string().value_unsafe()).value(); requested_assets.push_back(*v); }, }, member ); }); e.modified(component_id); } auto children_json = json["children"]; for (auto children : children_json.get_array()) { if (children.error()) { continue; } if (!json_to_entity(self, e, children.value_unsafe(), requested_assets).second) { return {{}, false}; } } return {e, true}; } auto ComponentDB::import_module(this ComponentDB& self, flecs::entity module) -> void { ZoneScoped; self.imported_modules.emplace_back(module); module.children([&](flecs::id id) { self.components.push_back(id); }); } auto ComponentDB::is_component_known(this ComponentDB& self, flecs::id component_id) -> bool { ZoneScoped; return std::ranges::any_of(self.components, [&](const auto& id) { return id == component_id; }); } auto ComponentDB::get_components(this ComponentDB& self) -> std::span<flecs::id> { return self.components; } Scene::Scene(const std::string& name) { init(name); } Scene::~Scene() { if (running) runtime_stop(); for (auto& [uuid, system] : lua_systems) { system->on_remove(this); } world.release(); lua_systems.clear(); auto& lua_manager = App::mod<LuaManager>(); lua_manager.get_state()->collect_gc(); } auto Scene::init(this Scene& self, const std::string& name) -> void { ZoneScoped; self.scene_name = name; self.component_db.import_module(self.world.import <Core>()); auto& renderer = App::mod<Renderer>(); self.renderer_instance = renderer.new_instance(&self); self.world.observer<TransformComponent>() .event(flecs::OnSet) .event(flecs::OnAdd) .event(flecs::OnRemove) .each([&self](flecs::iter& it, usize i, TransformComponent&) { auto entity = it.entity(i); if (it.event() == flecs::OnSet) { self.set_dirty(entity); } else if (it.event() == flecs::OnAdd) { self.add_transform(entity); self.set_dirty(entity); } else if (it.event() == flecs::OnRemove) { self.remove_transform(entity); } }); self.world.observer<TransformComponent, MeshComponent>() .event(flecs::OnAdd) .event(flecs::OnSet) .event(flecs::OnRemove) .each([&self](flecs::iter& it, usize i, TransformComponent& tc, MeshComponent& mc) { auto entity = it.entity(i); const auto mesh_event = it.event_id() == self.world.component<MeshComponent>(); if (it.event() == flecs::OnSet) { if (!self.entity_transforms_map.contains(entity)) self.add_transform(entity); self.set_dirty(entity); if (mesh_event && mc.mesh_uuid) self.attach_mesh(entity, mc.mesh_uuid, mc.mesh_index); } else if (it.event() == flecs::OnAdd) { self.add_transform(entity); self.set_dirty(entity); } else if (it.event() == flecs::OnRemove) { if (mc.mesh_uuid) self.detach_mesh(entity, mc.mesh_uuid, mc.mesh_index); self.remove_transform(entity); } }); self.world.observer<TransformComponent, SpriteComponent>() .event(flecs::OnSet) .event(flecs::OnAdd) .each([&self](flecs::iter& it, usize i, TransformComponent&, SpriteComponent& sprite) { auto entity = it.entity(i); // Set sprite rect if (auto id = self.get_entity_transform_id(entity)) { if (auto* transform = self.get_entity_transform(*id)) { sprite.rect = AABB(glm::vec3(-0.5, -0.5, -0.5), glm::vec3(0.5, 0.5, 0.5)); sprite.rect = sprite.rect.get_transformed(transform->world); } } }); self.world.observer<SpriteComponent>().event(flecs::OnAdd).each([](flecs::iter& it, usize i, SpriteComponent& c) { auto& asset_man = App::mod<AssetManager>(); if (it.event() == flecs::OnAdd) { c.material = asset_man.create_asset(AssetType::Material, {}); asset_man.load_material(c.material, Material{}); } }); self.world.observer<SpriteComponent>() .event(flecs::OnRemove) .with<AssetOwner>() .each([](flecs::iter& it, usize i, SpriteComponent& c) { auto& asset_man = App::mod<AssetManager>(); if (it.event() == flecs::OnRemove) { if (auto* material_asset = asset_man.get_asset(c.material)) { asset_man.unload_asset(material_asset->uuid); } } }); self.world.observer<AudioListenerComponent>() .event(flecs::OnSet) .event(flecs::OnAdd) .each([](flecs::iter& it, usize i, AudioListenerComponent& c) { auto& audio_engine = App::mod<AudioEngine>(); audio_engine.set_listener_cone(c.listener_index, c.cone_inner_angle, c.cone_outer_angle, c.cone_outer_gain); }); self.world.observer<AudioSourceComponent>() .event(flecs::OnSet) .event(flecs::OnAdd) .each([](flecs::iter& it, usize i, AudioSourceComponent& c) { auto& asset_man = App::mod<AssetManager>(); auto* audio_asset = asset_man.get_audio(c.audio_source); if (!audio_asset) return; auto& audio_engine = App::mod<AudioEngine>(); audio_engine.set_source_volume(audio_asset->get_source(), c.volume); audio_engine.set_source_pitch(audio_asset->get_source(), c.pitch); audio_engine.set_source_looping(audio_asset->get_source(), c.looping); audio_engine.set_source_attenuation_model( audio_asset->get_source(), static_cast<AudioEngine::AttenuationModelType>(c.attenuation_model) ); audio_engine.set_source_roll_off(audio_asset->get_source(), c.roll_off); audio_engine.set_source_min_gain(audio_asset->get_source(), c.min_gain); audio_engine.set_source_max_gain(audio_asset->get_source(), c.max_gain); audio_engine.set_source_min_distance(audio_asset->get_source(), c.min_distance); audio_engine.set_source_max_distance(audio_asset->get_source(), c.max_distance); audio_engine .set_source_cone(audio_asset->get_source(), c.cone_inner_angle, c.cone_outer_angle, c.cone_outer_gain); }); self.world.observer<SpriteAnimationComponent>() .event(flecs::OnSet) .event(flecs::OnAdd) .each([](flecs::iter& it, usize i, SpriteAnimationComponent& c) { c.reset(); }); self.world.observer<MeshComponent>() .with<AssetOwner>() .event(flecs::OnRemove) .each([](flecs::iter& it, usize i, MeshComponent& c) { ZoneScopedN("MeshComponent AssetOwner handling"); auto& asset_man = App::mod<AssetManager>(); asset_man.unload_asset(c.mesh_uuid); }); self.world.observer<AudioSourceComponent>() .with<AssetOwner>() .event(flecs::OnRemove) .each([](flecs::iter& it, usize i, AudioSourceComponent& c) { ZoneScopedN("AudioSourceComponent AssetOwner handling"); auto& asset_man = App::mod<AssetManager>(); asset_man.unload_asset(c.audio_source); }); self.world.observer<RigidBodyComponent>() .event(flecs::OnSet) .event(flecs::OnRemove) .each([&self](flecs::iter& it, usize i, RigidBodyComponent& rb) { ZoneScopedN("Rigidbody observer"); if (!self.is_running()) return; if (it.event() == flecs::OnSet) { auto entity = it.entity(i); auto& tc = entity.get<TransformComponent>(); self.create_rigidbody(it.entity(i), tc, rb); } else if (it.event() == flecs::OnRemove) { auto& physics = App::mod<Physics>(); auto& body_interface = physics.get_body_interface(); if (rb.runtime_body) { auto body_id = static_cast<JPH::Body*>(rb.runtime_body)->GetID(); body_interface.RemoveBody(body_id); body_interface.DestroyBody(body_id); rb.runtime_body = nullptr; } } }); self.world.observer<CharacterControllerComponent>() .event(flecs::OnSet) .event(flecs::OnRemove) .each([&self](flecs::iter& it, usize i, CharacterControllerComponent& ch) { ZoneScopedN("CharacterController observer"); if (!self.is_running()) return; if (it.event() == flecs::OnSet) { auto entity = it.entity(i); auto& tc = entity.get<TransformComponent>(); self.create_character_controller(entity, tc, ch); } else if (it.event() == flecs::OnRemove) { auto& physics = App::mod<Physics>(); JPH::BodyInterface& body_interface = physics.get_physics_system()->GetBodyInterface(); if (ch.character) { auto* character = reinterpret_cast<JPH::Character*>(ch.character); body_interface.RemoveBody(character->GetBodyID()); ch.character = nullptr; } } }); self.world.observer<ParticleSystemComponent>() .event(flecs::OnSet) .event(flecs::OnAdd) .event(flecs::OnRemove) .each([](flecs::iter& it, usize i, ParticleSystemComponent& c) { auto& asset_man = App::mod<AssetManager>(); if (it.event() == flecs::OnAdd) { if (c.play_on_awake) { c.system_time = 0.0f; c.playing = true; } if (!c.material) c.material = asset_man.create_asset(AssetType::Material, {}); asset_man.load_material(c.material, Material{}); auto parent = it.entity(i); for (u32 k = 0; k < c.max_particles; k++) { auto particle = it.world().entity().set<TransformComponent>({{}, {}, {0.5f, 0.5f, 0.5f}}); particle.set<ParticleComponent>({.life_remaining = c.start_lifetime}); c.particles.emplace_back(particle); particle.child_of(parent); } } else if (it.event() == flecs::OnRemove) { for (auto p : c.particles) { flecs::entity e{it.world(), p}; e.destruct(); } } else if (it.event() == flecs::OnSet) { if (auto* asset = asset_man.get_asset(c.material)) { if (!asset->is_loaded()) { asset_man.load_material(c.material, Material{}); } } asset_man.set_material_dirty(c.material); } }); self.world.observer<ParticleSystemComponent>() .event(flecs::OnRemove) .with<AssetOwner>() .each([](flecs::iter& it, usize i, ParticleSystemComponent& c) { auto& asset_man = App::mod<AssetManager>(); if (it.event() == flecs::OnRemove) { if (auto* material_asset = asset_man.get_asset(c.material)) { asset_man.unload_asset(material_asset->uuid); } } }); // Systems run order: // -- PreUpdate -> Main Systems // -- OnUpdate -> Physics Systems // -- PostUpdate -> Renderer Systems // --- Main Systems --- self.world.system<const TransformComponent, AudioListenerComponent>("audio_listener_update") .kind(flecs::PreUpdate) .each([&self](const flecs::entity& e, const TransformComponent& tc, AudioListenerComponent& ac) { if (ac.active) { auto& audio_engine = App::mod<AudioEngine>(); const glm::mat4 inverted = glm::inverse(self.get_world_transform(e)); const glm::vec3 forward = normalize(glm::vec3(inverted[2])); audio_engine.set_listener_position(ac.listener_index, tc.position); audio_engine.set_listener_direction(ac.listener_index, -forward); audio_engine.set_listener_cone(ac.listener_index, ac.cone_inner_angle, ac.cone_outer_angle, ac.cone_outer_gain); } }); self.world.system<const TransformComponent, AudioSourceComponent>("audio_source_update") .kind(flecs::PreUpdate) .each([](const flecs::entity& e, const TransformComponent& tc, const AudioSourceComponent& ac) { auto& asset_man = App::mod<AssetManager>(); if (auto* audio = asset_man.get_audio(ac.audio_source)) { auto& audio_engine = App::mod<AudioEngine>(); audio_engine.set_source_attenuation_model( audio->get_source(), static_cast<AudioEngine::AttenuationModelType>(ac.attenuation_model) ); audio_engine.set_source_volume(audio->get_source(), ac.volume); audio_engine.set_source_pitch(audio->get_source(), ac.pitch); audio_engine.set_source_looping(audio->get_source(), ac.looping); audio_engine.set_source_spatialization(audio->get_source(), ac.looping); audio_engine.set_source_roll_off(audio->get_source(), ac.roll_off); audio_engine.set_source_min_gain(audio->get_source(), ac.min_gain); audio_engine.set_source_max_gain(audio->get_source(), ac.max_gain); audio_engine.set_source_min_distance(audio->get_source(), ac.min_distance); audio_engine.set_source_max_distance(audio->get_source(), ac.max_distance); audio_engine.set_source_cone(audio->get_source(), ac.cone_inner_angle, ac.cone_outer_angle, ac.cone_outer_gain); audio_engine.set_source_doppler_factor(audio->get_source(), ac.doppler_factor); } }); // --- Physics Systems --- // TODOs(hatrickek): // Interpolation for rigibodies. const auto physics_tick_source = self.world.timer().interval(self.physics_interval); self.world .system("physics_step") // .kind(flecs::OnUpdate) .tick_source(physics_tick_source) .run([](flecs::iter& it) { auto& physics = App::mod<Physics>(); physics.step(it.delta_time()); }); self.world.system<TransformComponent, RigidBodyComponent>("rigidbody_update") .kind(flecs::OnUpdate) .tick_source(physics_tick_source) .each([](const flecs::entity& e, TransformComponent& tc, RigidBodyComponent& rb) { if (!rb.runtime_body) return; auto& physics = App::mod<Physics>(); const auto* body = static_cast<const JPH::Body*>(rb.runtime_body); const auto& body_interface = physics.get_physics_system()->GetBodyInterface(); if (!body_interface.IsActive(body->GetID())) return; const JPH::Vec3 position = body->GetPosition(); const JPH::Vec3 rotation = body->GetRotation().GetEulerAngles(); rb.previous_translation = rb.translation; rb.previous_rotation = rb.rotation; rb.translation = {position.GetX(), position.GetY(), position.GetZ()}; rb.rotation = glm::vec3(rotation.GetX(), rotation.GetY(), rotation.GetZ()); tc.position = rb.translation; tc.rotation = glm::eulerAngles(rb.rotation); e.modified<TransformComponent>(); }); self.world.system<TransformComponent, CharacterControllerComponent>("character_controller_update") .kind(flecs::OnUpdate) .tick_source(physics_tick_source) .each([](const flecs::entity& e, TransformComponent& tc, CharacterControllerComponent& ch) { auto* character = reinterpret_cast<JPH::Character*>(ch.character); OX_CHECK_NULL(character); character->PostSimulation(ch.collision_tolerance); const JPH::Vec3 position = character->GetPosition(); const JPH::Vec3 rotation = character->GetRotation().GetEulerAngles(); ch.previous_translation = ch.translation; ch.previous_rotation = ch.rotation; ch.translation = {position.GetX(), position.GetY(), position.GetZ()}; ch.rotation = glm::vec3(rotation.GetX(), rotation.GetY(), rotation.GetZ()); tc.position = ch.translation; tc.rotation = glm::eulerAngles(ch.rotation); e.modified<TransformComponent>(); }); // -- Renderer Systems --- self.world.system<const TransformComponent, ParticleSystemComponent>("particle_system_update") .kind(flecs::PostUpdate) .each([](flecs::iter& it, usize i, const TransformComponent& tc, ParticleSystemComponent& component) { const auto emit = [&it, &component](flecs::entity parent, glm::vec3 position, u32 count) { if (component.active_particle_count >= component.max_particles) return; for (uint32_t pool_idx = 0; pool_idx < count; ++pool_idx) { if (++component.pool_index >= component.max_particles) component.pool_index = 0; auto particle = flecs::entity{it.world(), component.particles[component.pool_index]}; const auto random_float = [](f32 min, f32 max) { static Random random = {}; f32 r = random.get_float(); return min + r * (max - min); }; auto new_position = position; new_position.x += random_float(component.position_start.x, component.position_end.x); new_position.y += random_float(component.position_start.y, component.position_end.y); new_position.z += random_float(component.position_start.z, component.position_end.z); particle.set<TransformComponent>({new_position}); particle.set<ParticleComponent>({.life_remaining = component.start_lifetime}); } }; OX_CHECK_EQ(component.particles.size(), component.max_particles); auto entity = it.entity(i); const float sim_ts = it.delta_time() * component.simulation_speed; if (component.playing && !component.looping) component.system_time += sim_ts; const float delay = component.start_delay; if (component.playing && (component.looping || (component.system_time <= delay + component.duration && component.system_time > delay))) { // Emit particles in unit time component.spawn_time += sim_ts; if (component.spawn_time >= 1.0f / static_cast<float>(component.rate_over_time)) { component.spawn_time = 0.0f; emit(entity, tc.position, 1); } // Emit particles over unit distance if (glm::distance2(component.last_spawned_position, tc.position) > 1.0f) { component.last_spawned_position = tc.position; emit(entity, tc.position, component.rate_over_distance); } // Emit bursts of particles over time component.burst_time += sim_ts; if (component.burst_time >= component.burst_time) { component.burst_time = 0.0f; emit(entity, tc.position, component.burst_count); } } component.active_particle_count = 0; }); self.world.system<TransformComponent, ParticleComponent>("particle_update") .kind(flecs::PostUpdate) .each([](flecs::iter& it, usize i, TransformComponent& particle_tc, ParticleComponent& particle) { if (particle.life_remaining <= 0.0f) return; auto evaluate_over_time = []<typename T>(T start, T end, f32 factor) -> T { return glm::lerp(end, start, factor); }; auto evaluate_by_speed = []<typename T>(T start, T end, f32 min_speed, f32 max_speed, f32 speed) -> T { f32 factor = math::inverse_lerp_clamped(min_speed, max_speed, speed); return glm::lerp(end, start, factor); }; auto particle_entity = it.entity(i); auto parent = particle_entity.parent(); auto component = parent.get<ParticleSystemComponent>(); float sim_ts = it.delta_time() * component.simulation_speed; particle.life_remaining -= sim_ts; const float t = glm::clamp(particle.life_remaining / component.start_lifetime, 0.0f, 1.0f); glm::vec3 velocity = component.start_velocity; if (component.velocity_over_lifetime_enabled) velocity *= evaluate_over_time(component.velocity_over_lifetime_start, component.velocity_over_lifetime_end, t); glm::vec3 force(0.0f); if (component.force_over_lifetime_enabled) force = evaluate_over_time(component.force_over_lifetime_start, component.force_over_lifetime_end, t); force.y += component.gravity_modifier * -9.8f; velocity += force * sim_ts; const float velocity_magnitude = glm::length(velocity); // Color particle.color = component.start_color; if (component.color_over_lifetime_enabled) particle.color *= evaluate_over_time(component.color_over_lifetime_start, component.color_over_lifetime_end, t); if (component.color_by_speed_enabled) particle.color *= evaluate_by_speed( component.color_by_speed_start, component.color_by_speed_end, component.color_by_speed_min_speed, component.color_by_speed_max_speed, velocity_magnitude ); // Size particle_tc.scale = component.start_size; if (component.size_over_lifetime_enabled) particle_tc .scale *= evaluate_over_time(component.size_over_lifetime_start, component.size_over_lifetime_end, t); if (component.size_by_speed_enabled) particle_tc.scale *= evaluate_by_speed( component.size_by_speed_start, component.size_by_speed_end, component.size_by_speed_min_speed, component.size_by_speed_max_speed, velocity_magnitude ); // Rotation particle_tc.rotation = component.start_rotation; if (component.rotation_over_lifetime_enabled) particle_tc.rotation += evaluate_over_time( component.rotation_over_lifetime_start, component.rotation_over_lifetime_end, t ); if (component.rotation_by_speed_enabled) particle_tc.rotation += evaluate_by_speed( component.rotation_by_speed_start, component.rotation_by_speed_end, component.rotation_by_speed_min_speed, component.rotation_by_speed_max_speed, velocity_magnitude ); particle_tc.position += velocity * sim_ts; particle_entity.modified<TransformComponent>(); ++component.active_particle_count; }); self.world.system<const TransformComponent, CameraComponent>("camera_update") .kind(flecs::PostUpdate) .each([](const TransformComponent& tc, CameraComponent& cc) { const auto screen_extent = App::get()->get_swapchain_extent(); cc.position = tc.position; cc.pitch = tc.rotation.x; cc.yaw = tc.rotation.y; Camera::update(cc, screen_extent); }); self.world.system<const TransformComponent, MeshComponent>("meshes_update") .kind(flecs::PostUpdate) .each([](const TransformComponent& tc, MeshComponent& mc) {}); self.world.system<SpriteComponent>("sprite_update") .kind(flecs::PostUpdate) .each([](const flecs::entity entity, SpriteComponent& sprite) { if (RendererCVar::cvar_draw_bounding_boxes.get()) { DebugRenderer::draw_aabb(sprite.rect, glm::vec4(1, 1, 1, 1.0f)); } }); self.world.system<SpriteComponent, SpriteAnimationComponent>("sprite_animation_update") .kind(flecs::PostUpdate) .each([](flecs::iter& it, size_t, SpriteComponent& sprite, SpriteAnimationComponent& sprite_animation) { auto& asset_manager = App::mod<AssetManager>(); auto* material = asset_manager.get_material(sprite.material); if (sprite_animation.num_frames < 1 || sprite_animation.fps < 1 || sprite_animation.columns < 1 || !material || !material->albedo_texture) return; const auto dt = glm::clamp(static_cast<float>(it.delta_time()), 0.0f, 0.25f); const auto time = sprite_animation.current_time + dt; sprite_animation.current_time = time; const float duration = static_cast<float>(sprite_animation.num_frames) / sprite_animation.fps; u32 frame = math::flooru32(sprite_animation.num_frames * (time / duration)); if (time > duration) { if (sprite_animation.inverted) { // Remove/add a frame depending on the direction const float frame_length = 1.0f / sprite_animation.fps; sprite_animation.current_time -= duration - frame_length; } else { sprite_animation.current_time -= duration; } } if (sprite_animation.loop) frame %= sprite_animation.num_frames; else frame = glm::min(frame, sprite_animation.num_frames - 1); frame = sprite_animation.inverted ? sprite_animation.num_frames - 1 - frame : frame; const u32 frame_x = frame % sprite_animation.columns; const u32 frame_y = frame / sprite_animation.columns; const auto* albedo_texture = asset_manager.get_texture(material->albedo_texture); auto& uv_size = material->uv_size; auto texture_size = glm::vec2(albedo_texture->get_extent().width, albedo_texture->get_extent().height); uv_size = { sprite_animation.frame_size[0] * 1.f / texture_size[0], sprite_animation.frame_size[1] * 1.f / texture_size[1] }; material->uv_offset = material->uv_offset + glm::vec2{uv_size.x * frame_x, uv_size.y * frame_y}; }); auto& asset_man = App::mod<AssetManager>(); asset_man.set_all_materials_dirty(); } auto Scene::physics_init(this Scene& self) -> void { ZoneScoped; // Remove old bodies and reset callbacks self.physics_deinit(); self.body_activation_listener_3d = std::make_unique<Physics3DBodyActivationListener>(); self.contact_listener_3d = std::make_unique<Physics3DContactListener>(&self); const auto physics_system = App::mod<Physics>().get_physics_system(); physics_system->SetBodyActivationListener(self.body_activation_listener_3d.get()); physics_system->SetContactListener(self.contact_listener_3d.get()); // Rigidbodies self.world.query_builder<const TransformComponent, RigidBodyComponent>().build().each( [&self](flecs::entity e, const TransformComponent& tc, RigidBodyComponent& rb) { if (rb.runtime_body == nullptr) { rb.previous_translation = rb.translation = tc.position; rb.previous_rotation = rb.rotation = tc.rotation; self.create_rigidbody(e, tc, rb); } } ); // Characters self.world.query_builder<const TransformComponent, CharacterControllerComponent>().build().each( [&self](flecs::entity e, const TransformComponent& tc, CharacterControllerComponent& ch) { if (ch.character == nullptr) { self.create_character_controller(e, tc, ch); } } ); physics_system->OptimizeBroadPhase(); } auto Scene::physics_deinit(this Scene& self) -> void { ZoneScoped; auto& physics = App::mod<Physics>(); self.world.query_builder<RigidBodyComponent>().build().each( [&physics](const flecs::entity& e, RigidBodyComponent& rb) { if (rb.runtime_body) { JPH::BodyInterface& body_interface = physics.get_physics_system()->GetBodyInterface(); const auto* body = static_cast<const JPH::Body*>(rb.runtime_body); body_interface.RemoveBody(body->GetID()); body_interface.DestroyBody(body->GetID()); rb.runtime_body = nullptr; } } ); self.world.query_builder<CharacterControllerComponent>().build().each( [&physics](const flecs::entity& e, CharacterControllerComponent& ch) { if (ch.character) { JPH::BodyInterface& body_interface = physics.get_physics_system()->GetBodyInterface(); auto* character = reinterpret_cast<JPH::Character*>(ch.character); body_interface.RemoveBody(character->GetBodyID()); ch.character = nullptr; } } ); self.body_activation_listener_3d.reset(); self.contact_listener_3d.reset(); } auto Scene::runtime_start(this Scene& self) -> void { ZoneScoped; self.running = true; self.run_deferred_functions(); self.physics_init(); // Scripting for (auto& [uuid, system] : self.lua_systems) { system->on_scene_start(&self); } } auto Scene::runtime_stop(this Scene& self) -> void { ZoneScoped; self.running = false; self.physics_deinit(); // Scripting for (auto& [uuid, system] : self.lua_systems) { system->on_scene_stop(&self); } } auto Scene::runtime_update(this Scene& self, const Timestep& delta_time) -> void { ZoneScoped; self.run_deferred_functions(); auto pre_update_phase_enabled = !self.world.entity(flecs::PreUpdate).has(flecs::Disabled); auto on_update_phase_enabled = !self.world.entity(flecs::OnUpdate).has(flecs::Disabled); if (pre_update_phase_enabled && on_update_phase_enabled) { for (auto& [uuid, system] : self.lua_systems) { system->on_scene_update(&self, delta_time.get_seconds()); } } // TODO: Pass our delta_time? self.world.progress(); if (RendererCVar::cvar_enable_physics_debug_renderer.get()) { auto& physics = App::mod<Physics>(); physics.debug_draw(); } auto& asset_man = App::mod<AssetManager>(); auto meshlet_instance_visibility_offset = 0_u32; auto max_meshlet_instance_count = 0_u32; auto gpu_meshes = std::vector<GPU::Mesh>(); auto gpu_mesh_instances = std::vector<GPU::MeshInstance>(); if (self.meshes_dirty) { for (const auto& [rendering_mesh, transform_ids] : self.rendering_meshes_map) { auto* model = asset_man.get_model(rendering_mesh.first); if (!model) continue; const auto& mesh = model->meshes[rendering_mesh.second]; for (auto primitive_index : mesh.primitive_indices) { const auto& primitive = model->primitives[primitive_index]; const auto& gpu_mesh = model->gpu_meshes[primitive_index]; auto mesh_index = static_cast<u32>(gpu_meshes.size()); gpu_meshes.emplace_back(gpu_mesh); // ── INSTANCING ────────────────────────────────────────────────── for (const auto transform_id : transform_ids) { auto lod0_index = 0; const auto& lod0 = gpu_mesh.lods[lod0_index]; auto& mesh_instance = gpu_mesh_instances.emplace_back(); mesh_instance.mesh_index = mesh_index; mesh_instance.lod_index = lod0_index; mesh_instance.material_index = primitive.material_index; mesh_instance.transform_index = SlotMap_decode_id(transform_id).index; mesh_instance.meshlet_instance_visibility_offset = meshlet_instance_visibility_offset; meshlet_instance_visibility_offset += lod0.meshlet_count; max_meshlet_instance_count += lod0.meshlet_count; } } } self.mesh_instance_count = gpu_mesh_instances.size(); self.max_meshlet_instance_count = max_meshlet_instance_count; } auto uuid_to_image_index = [&](const UUID& uuid) -> option<u32> { if (!uuid || !asset_man.is_texture_loaded(uuid)) { return nullopt; } auto* texture = asset_man.get_texture(uuid); return texture->get_view_index(); }; auto dirty_material_ids = asset_man.get_dirty_material_ids(); auto dirty_material_indices = std::vector<u32>(); for (const auto dirty_id : dirty_material_ids) { const auto* material = asset_man.get_material(dirty_id); if (!material) continue; auto dirty_index = SlotMap_decode_id(dirty_id).index; dirty_material_indices.push_back(dirty_index); if (dirty_index >= self.gpu_materials.size()) { self.gpu_materials.resize(dirty_index + 1, {}); } auto albedo_image_index = uuid_to_image_index(material->albedo_texture); auto normal_image_index = uuid_to_image_index(material->normal_texture); auto emissive_image_index = uuid_to_image_index(material->emissive_texture); auto metallic_roughness_image_index = uuid_to_image_index(material->metallic_roughness_texture); auto occlusion_image_index = uuid_to_image_index(material->occlusion_texture); auto sampler_index = 0_u32; auto flags = GPU::MaterialFlag::None; if (albedo_image_index.has_value()) { flags |= GPU::MaterialFlag::HasAlbedoImage; // Incase we wanted to change a material's sampler after it's creation // we should prefer material's sampler over texture's default sampler. auto& vk_context = App::get_vkcontext(); auto* texture = asset_man.get_texture(material->albedo_texture); sampler_index = texture->get_sampler_index(); auto texture_sampler = vk_context.resources.samplers.slot(texture->get_sampler_id()); vuk::SamplerCreateInfo sampler_ci = {}; switch (material->sampling_mode) { case SamplingMode::LinearRepeated : sampler_ci = vuk::LinearSamplerRepeated; break; case SamplingMode::LinearClamped : sampler_ci = vuk::LinearSamplerClamped; break; case SamplingMode::NearestRepeated : sampler_ci = vuk::NearestSamplerRepeated; break; case SamplingMode::NearestClamped : sampler_ci = vuk::NearestSamplerClamped; break; case SamplingMode::LinearRepeatedAnisotropy: sampler_ci = vuk::LinearSamplerRepeatedAnisotropy; break; } auto material_sampler = vk_context.runtime->acquire_sampler(sampler_ci, vk_context.num_frames); if (texture_sampler->id != material_sampler.id) { auto sampler_id = vk_context.allocate_sampler(sampler_ci); auto sampler_index_from_material = SlotMap_decode_id(sampler_id).index; sampler_index = sampler_index_from_material; } } flags |= normal_image_index.has_value() ? GPU::MaterialFlag::HasNormalImage : GPU::MaterialFlag::None; flags |= emissive_image_index.has_value() ? GPU::MaterialFlag::HasEmissiveImage : GPU::MaterialFlag::None; flags |= metallic_roughness_image_index.has_value() ? GPU::MaterialFlag::HasMetallicRoughnessImage : GPU::MaterialFlag::None; flags |= occlusion_image_index.has_value() ? GPU::MaterialFlag::HasOcclusionImage : GPU::MaterialFlag::None; auto gpu_material = GPU::Material{ .albedo_color = material->albedo_color, .emissive_color = material->emissive_color, .roughness_factor = material->roughness_factor, .metallic_factor = material->metallic_factor, .alpha_cutoff = material->alpha_cutoff, .flags = flags, .sampler_index = sampler_index, .albedo_image_index = albedo_image_index.value_or(0_u32), .normal_image_index = normal_image_index.value_or(0_u32), .emissive_image_index = emissive_image_index.value_or(0_u32), .metallic_roughness_image_index = metallic_roughness_image_index.value_or(0_u32), .occlusion_image_index = occlusion_image_index.value_or(0_u32), .uv_size = material->uv_size, .uv_offset = material->uv_offset, }; self.gpu_materials[dirty_index] = gpu_material; } auto update_info = RendererInstanceUpdateInfo{ .mesh_instance_count = self.mesh_instance_count, .max_meshlet_instance_count = self.max_meshlet_instance_count, .dirty_transform_ids = self.dirty_transforms, .gpu_transforms = self.transforms.slots_unsafe(), .dirty_material_indices = dirty_material_indices, .gpu_materials = self.gpu_materials, .gpu_meshes = gpu_meshes, .gpu_mesh_instances = gpu_mesh_instances, }; self.renderer_instance->update(update_info); self.dirty_transforms.clear(); self.meshes_dirty = false; } auto Scene::get_lua_system(this const Scene& self, const UUID& lua_script) -> LuaSystem* { ZoneScoped; if (self.lua_systems.contains(lua_script)) { return self.lua_systems.at(lua_script); } return nullptr; } auto Scene::get_lua_systems(this const Scene& self) -> const ankerl::unordered_dense::map<UUID, LuaSystem*>& { ZoneScoped; return self.lua_systems; } auto Scene::add_lua_system(this Scene& self, const UUID& lua_script) -> void { ZoneScoped; auto& asset_man = App::mod<AssetManager>(); if (!asset_man.get_asset(lua_script)->is_loaded()) { asset_man.load_asset(lua_script); } auto* script_system = asset_man.get_script(lua_script); script_system->reload(); self.lua_systems.emplace(lua_script, script_system); script_system->on_add(&self); } auto Scene::remove_lua_system(this Scene& self, const UUID& lua_script) -> void { ZoneScoped; auto& asset_man = App::mod<AssetManager>(); auto* script_system = asset_man.get_script(lua_script); script_system->on_remove(&self); self.lua_systems.erase(lua_script); } auto Scene::defer_function(this Scene& self, const std::function<void(Scene* scene)>& func) -> void { ZoneScoped; self.deferred_functions_.emplace_back(func); } auto Scene::run_deferred_functions(this Scene& self) -> void { ZoneScoped; if (!self.deferred_functions_.empty()) { for (auto& func : self.deferred_functions_) { func(&self); } self.deferred_functions_.clear(); } } auto Scene::disable_phases(const std::vector<flecs::entity_t>& phases) -> void { ZoneScoped; for (auto& phase : phases) { if (!world.entity(phase).has(flecs::Disabled)) world.entity(phase).disable(); } } auto Scene::enable_all_phases() -> void { ZoneScoped; world.entity(flecs::PreUpdate).enable(); world.entity(flecs::OnUpdate).enable(); world.entity(flecs::PostUpdate).enable(); } void Scene::on_render(const vuk::Extent3D extent, const vuk::Format format) { ZoneScoped; for (auto& [uuid, system] : lua_systems) { system->on_scene_render(this, extent, format); } } auto Scene::on_viewport_render(vuk::Extent3D extent, vuk::Format format) -> void { ZoneScoped; if (!is_running()) return; for (auto& [uuid, system] : lua_systems) { system->on_viewport_render(this, extent, format); } } auto Scene::create_entity(const std::string& name, bool safe_naming) const -> flecs::entity { ZoneScoped; flecs::entity e = {}; if (name.empty()) { e = safe_naming ? world.entity(safe_entity_name("entity").c_str()) : world.entity(); } else { e = safe_naming ? world.entity(safe_entity_name(name).c_str()) : world.entity(name.c_str()); } return e.add<TransformComponent>().add<LayerComponent>(); } auto Scene::create_model_entity(this Scene& self, const UUID& asset_uuid) -> flecs::entity { ZoneScoped; auto& asset_man = App::mod<AssetManager>(); // sanity check if (!asset_man.get_asset(asset_uuid)) { OX_LOG_ERROR("Cannot import an invalid model '{}' into the scene!", asset_uuid.str()); return {}; } // acquire model if (!asset_man.load_model(asset_uuid)) { return {}; } auto* imported_model = asset_man.get_model(asset_uuid); auto& default_scene = imported_model->scenes[imported_model->default_scene_index]; auto root_entity = self.create_entity(default_scene.name, default_scene.name.empty() ? false : true); auto visit_nodes = [&self, // &imported_model, &asset_uuid](this auto& visitor, flecs::entity& root, std::vector<usize>& node_indices) -> void { for (const auto node_index : node_indices) { auto& cur_node = imported_model->nodes[node_index]; auto node_entity = self.create_entity(cur_node.name, cur_node.name.empty() ? false : true); const auto T = glm::translate(glm::mat4(1.0f), cur_node.translation); const auto R = glm::mat4_cast(cur_node.rotation); const auto S = glm::scale(glm::mat4(1.0f), cur_node.scale); auto TRS = T * R * S; auto transform_comp = TransformComponent{}; { glm::quat rotation = {}; glm::vec3 skew = {}; glm::vec4 perspective = {}; glm::decompose(TRS, transform_comp.scale, rotation, transform_comp.position, skew, perspective); transform_comp.rotation = glm::eulerAngles(glm::quat(rotation[3], rotation[0], rotation[1], rotation[2])); } node_entity.set(transform_comp); if (cur_node.mesh_index.has_value()) { node_entity.set<MeshComponent>( {.mesh_index = static_cast<u32>(cur_node.mesh_index.value()), .mesh_uuid = asset_uuid} ); } if (cur_node.light_index.has_value()) { auto& node_light = imported_model->lights[cur_node.light_index.value()]; auto lc = LightComponent{ .type = static_cast<LightComponent::LightType>(node_light.type), .color = node_light.color, .intensity = node_light.intensity, }; if (node_light.range.has_value()) { lc.radius = *node_light.range; } if (node_light.inner_cone_angle.has_value()) { lc.inner_cone_angle = *node_light.inner_cone_angle; } if (node_light.outer_cone_angle.has_value()) { lc.inner_cone_angle = *node_light.inner_cone_angle; } node_entity.set<LightComponent>(lc); } node_entity.child_of(root); node_entity.modified<TransformComponent>(); visitor(node_entity, cur_node.child_indices); } }; visit_nodes(root_entity, default_scene.node_indices); return root_entity; } auto Scene::copy(const std::shared_ptr<Scene>& src_scene) -> std::shared_ptr<Scene> { ZoneScoped; // Copies the world but not the renderer instance. // NOTE: Assumes the assets in src_scene are already loaded. std::shared_ptr<Scene> new_scene = std::make_shared<Scene>(src_scene->scene_name); new_scene->scene_name = "Scene_Copy"; JsonWriter writer{}; writer.begin_obj(); writer["scripts"].begin_array(); for (auto& [uuid, system] : src_scene->lua_systems) { writer.begin_obj(); writer["uuid"] = uuid.str(); writer.end_obj(); } writer.end_array(); writer["entities"].begin_array(); src_scene->world.query_builder().with<TransformComponent>().build().each([&writer](flecs::entity e) { if (e.parent() == flecs::entity::null() && !e.has<Hidden>()) { entity_to_json(writer, e); } }); writer.end_array(); writer.end_obj(); auto content = simdjson::padded_string(writer.stream.str()); simdjson::ondemand::parser parser; auto doc = parser.iterate(content); if (doc.error()) { OX_LOG_ERROR("Failed to parse scene file! {}", simdjson::error_message(doc.error())); return nullptr; } std::vector<UUID> requested_assets = {}; auto scripts_array = doc["scripts"]; for (auto script_json : scripts_array.get_array()) { auto uuid_json = script_json.value_unsafe(); auto script_uuid = UUID::from_string(uuid_json["uuid"].get_string().value_unsafe()).value(); requested_assets.emplace_back(script_uuid); new_scene->add_lua_system(script_uuid); } auto entities_array = doc["entities"]; for (auto entity_json : entities_array.get_array()) { if (!json_to_entity(*new_scene, flecs::entity::null(), entity_json.value_unsafe(), requested_assets).second) { return nullptr; } } new_scene->meshes_dirty = true; return new_scene; } auto Scene::get_world_position(const flecs::entity entity) -> glm::vec3 { const auto& tc = entity.get<TransformComponent>(); const auto parent = entity.parent(); if (parent != flecs::entity::null()) { const glm::vec3 parent_position = get_world_position(parent); const auto& parent_tc = parent.get<TransformComponent>(); const glm::quat parent_rotation = glm::quat(parent_tc.rotation); const glm::vec3 rotated_scaled_pos = parent_rotation * (parent_tc.scale * tc.position); return parent_position + rotated_scaled_pos; } return tc.position; } auto Scene::get_world_transform(const flecs::entity entity) -> glm::mat4 { const auto& tc = entity.get<TransformComponent>(); const auto parent = entity.parent(); const glm::mat4 parent_transform = parent != flecs::entity::null() ? get_world_transform(parent) : glm::mat4(1.0f); return parent_transform * glm::translate(glm::mat4(1.0f), tc.position) * glm::toMat4(glm::quat(tc.rotation)) * glm::scale(glm::mat4(1.0f), tc.scale); } auto Scene::get_local_transform(flecs::entity entity) -> glm::mat4 { const auto& tc = entity.get<TransformComponent>(); return glm::translate(glm::mat4(1.0f), tc.position) * glm::toMat4(glm::quat(tc.rotation)) * glm::scale(glm::mat4(1.0f), tc.scale); } auto Scene::set_dirty(this Scene& self, flecs::entity entity) -> void { ZoneScoped; auto visit_parent = [](this auto& visitor, Scene& s, flecs::entity e) -> glm::mat4 { auto local_mat = glm::mat4(1.0f); if (e.has<TransformComponent>()) { local_mat = s.get_local_transform(e); } auto parent = e.parent(); if (parent) { return visitor(s, parent) * local_mat; } else { return local_mat; } }; OX_ASSERT(entity.has<TransformComponent>()); auto it = self.entity_transforms_map.find(entity); if (it == self.entity_transforms_map.end()) { return; } auto transform_id = it->second; auto* gpu_transform = self.transforms.slot(transform_id); gpu_transform->local = glm::mat4(1.0f); gpu_transform->world = visit_parent(self, entity); gpu_transform->normal = glm::mat3(gpu_transform->world); self.dirty_transforms.push_back(transform_id); // notify children entity.children([](flecs::entity e) { if (e.has<TransformComponent>()) { e.modified<TransformComponent>(); } }); } auto Scene::get_entity_transform_id(flecs::entity entity) const -> option<GPU::TransformID> { auto it = entity_transforms_map.find(entity); if (it == entity_transforms_map.end()) return nullopt; return it->second; } auto Scene::get_entity_transform(GPU::TransformID transform_id) const -> const GPU::Transforms* { return transforms.slotc(transform_id); } auto Scene::add_transform(this Scene& self, flecs::entity entity) -> GPU::TransformID { ZoneScoped; auto id = self.transforms.create_slot(); self.entity_transforms_map.emplace(entity, id); self.transform_index_entities_map.emplace(SlotMap_decode_id(id).index, entity); return id; } auto Scene::remove_transform(this Scene& self, flecs::entity entity) -> void { ZoneScoped; auto it = self.entity_transforms_map.find(entity); if (it == self.entity_transforms_map.end()) { return; } self.transform_index_entities_map.erase(SlotMap_decode_id(it->second).index); self.transforms.destroy_slot(it->second); self.entity_transforms_map.erase(it); } auto Scene::attach_mesh(this Scene& self, flecs::entity entity, const UUID& mesh_uuid, usize mesh_index) -> bool { ZoneScoped; auto transforms_it = self.entity_transforms_map.find(entity); if (!self.entity_transforms_map.contains(entity)) { OX_LOG_FATAL("Target entity must have a transform component!"); return false; } const auto transform_id = transforms_it->second; auto old_mesh_uuid = std::ranges::find_if(self.rendering_meshes_map, [transform_id](const auto& entry) { const auto& [_, transform_ids] = entry; return std::ranges::contains(transform_ids, transform_id); }); if (old_mesh_uuid != self.rendering_meshes_map.end()) { self.detach_mesh(entity, old_mesh_uuid->first.first, mesh_index); } auto [instances_it, inserted] = self.rendering_meshes_map.try_emplace(std::pair{mesh_uuid, mesh_index}); if (!inserted && instances_it == self.rendering_meshes_map.end()) { return false; } instances_it->second.emplace_back(transform_id); self.meshes_dirty = true; self.set_dirty(entity); return true; } auto Scene::detach_mesh(this Scene& self, flecs::entity entity, const UUID& mesh_uuid, usize mesh_index) -> bool { ZoneScoped; auto instances_it = self.rendering_meshes_map.find(std::pair(mesh_uuid, mesh_index)); auto transforms_it = self.entity_transforms_map.find(entity); if (instances_it == self.rendering_meshes_map.end() || transforms_it == self.entity_transforms_map.end()) { return false; } const auto transform_id = transforms_it->second; auto& instances = instances_it->second; std::erase_if(instances, [transform_id](const GPU::TransformID& id) { return id == transform_id; }); self.meshes_dirty = true; if (instances.empty()) { self.rendering_meshes_map.erase(instances_it); } return true; } auto Scene::on_contact_added( const JPH::Body& body1, const JPH::Body& body2, const JPH::ContactManifold& manifold, const JPH::ContactSettings& settings ) -> void { ZoneScoped; auto write_lock = std::unique_lock(physics_mutex); for (auto& [uuid, system] : lua_systems) { system->on_contact_added(this, body1, body2, manifold, settings); } } auto Scene::on_contact_persisted( const JPH::Body& body1, const JPH::Body& body2, const JPH::ContactManifold& manifold, const JPH::ContactSettings& settings ) -> void { ZoneScoped; auto write_lock = std::unique_lock(physics_mutex); for (auto& [uuid, system] : lua_systems) { system->on_contact_persisted(this, body1, body2, manifold, settings); } } auto Scene::on_contact_removed(const JPH::SubShapeIDPair& sub_shape_pair) -> void { ZoneScoped; auto write_lock = std::unique_lock(physics_mutex); for (auto& [uuid, system] : lua_systems) { system->on_contact_removed(this, sub_shape_pair); } } auto Scene::on_body_activated(const JPH::BodyID& body_id, JPH::uint64 body_user_data) -> void { ZoneScoped; auto write_lock = std::unique_lock(physics_mutex); for (auto& [uuid, system] : lua_systems) { system->on_body_activated(this, body_id, (u64)body_user_data); } } auto Scene::on_body_deactivated(const JPH::BodyID& body_id, JPH::uint64 body_user_data) -> void { ZoneScoped; auto write_lock = std::unique_lock(physics_mutex); for (auto& [uuid, system] : lua_systems) { system->on_body_deactivated(this, body_id, (u64)body_user_data); } } auto Scene::create_rigidbody(flecs::entity entity, const TransformComponent& transform, RigidBodyComponent& component) -> void { ZoneScoped; auto& physics = App::mod<Physics>(); auto& body_interface = physics.get_body_interface(); if (component.runtime_body) { auto body_id = static_cast<JPH::Body*>(component.runtime_body)->GetID(); body_interface.RemoveBody(body_id); body_interface.DestroyBody(body_id); component.runtime_body = nullptr; } JPH::MutableCompoundShapeSettings compound_shape_settings = {}; float max_scale_component = glm::max(glm::max(transform.scale.x, transform.scale.y), transform.scale.z); const auto entity_name = std::string(entity.name()); JPH::ShapeSettings::ShapeResult shape_result = {}; glm::vec3 offset = {}; if (const auto* bc = entity.try_get<BoxColliderComponent>()) { const JPH::Ref<PhysicsMaterial3D> mat = new PhysicsMaterial3D(entity_name, JPH::ColorArg(255, 0, 0), bc->friction, bc->restitution); glm::vec3 scale = bc->size; JPH::BoxShapeSettings shape_settings({glm::abs(scale.x), glm::abs(scale.y), glm::abs(scale.z)}, 0.05f, mat); shape_settings.SetDensity(glm::max(0.001f, bc->density)); shape_result = shape_settings.Create(); offset = bc->offset; } else if (const auto* scc = entity.try_get<SphereColliderComponent>()) { const JPH::Ref<PhysicsMaterial3D> mat = new PhysicsMaterial3D(entity_name, JPH::ColorArg(255, 0, 0), scc->friction, scc->restitution); float radius = 2.0f * scc->radius * max_scale_component; JPH::SphereShapeSettings shape_settings(glm::max(0.01f, radius), mat); shape_settings.SetDensity(glm::max(0.001f, scc->density)); shape_result = shape_settings.Create(); offset = scc->offset; } else if (const auto* ccc = entity.try_get<CapsuleColliderComponent>()) { const JPH::Ref<PhysicsMaterial3D> mat = new PhysicsMaterial3D(entity_name, JPH::ColorArg(255, 0, 0), ccc->friction, ccc->restitution); float radius = 2.0f * ccc->radius * max_scale_component; JPH::CapsuleShapeSettings shape_settings(glm::max(0.01f, ccc->height) * 0.5f, glm::max(0.01f, radius), mat); shape_settings.SetDensity(glm::max(0.001f, ccc->density)); shape_result = shape_settings.Create(); offset = ccc->offset; } else if (const auto* tcc = entity.try_get<TaperedCapsuleColliderComponent>()) { const JPH::Ref<PhysicsMaterial3D> mat = new PhysicsMaterial3D(entity_name, JPH::ColorArg(255, 0, 0), tcc->friction, tcc->restitution); float top_radius = 2.0f * tcc->top_radius * max_scale_component; float bottom_radius = 2.0f * tcc->bottom_radius * max_scale_component; JPH::TaperedCapsuleShapeSettings shape_settings( glm::max(0.01f, tcc->height) * 0.5f, glm::max(0.01f, top_radius), glm::max(0.01f, bottom_radius), mat ); shape_settings.SetDensity(glm::max(0.001f, tcc->density)); shape_result = shape_settings.Create(); offset = tcc->offset; } else if (const auto* cycc = entity.try_get<CylinderColliderComponent>()) { const JPH::Ref<PhysicsMaterial3D> mat = new PhysicsMaterial3D(entity_name, JPH::ColorArg(255, 0, 0), cycc->friction, cycc->restitution); float radius = 2.0f * cycc->radius * max_scale_component; JPH::CylinderShapeSettings shape_settings(glm::max(0.01f, cycc->height) * 0.5f, glm::max(0.01f, radius), 0.05f, mat); shape_settings.SetDensity(glm::max(0.001f, cycc->density)); shape_result = shape_settings.Create(); offset = cycc->offset; } if (shape_result.HasError()) { OX_LOG_ERROR("Jolt shape error: {}", shape_result.GetError().c_str()); } if (!shape_result.IsEmpty()) { compound_shape_settings.AddShape({offset.x, offset.y, offset.z}, JPH::Quat::sIdentity(), shape_result.Get()); } else { return; // No Shape } // Body auto rotation = glm::quat(transform.rotation); u8 layer_index = 1; // Default Layer if (const auto* layer_component = entity.try_get<LayerComponent>()) { layer_index = layer_component->layer; } auto compound_shape = compound_shape_settings.Create(); if (compound_shape.HasError()) { OX_LOG_ERROR("Jolt shape error: {}", compound_shape.GetError().c_str()); } JPH::BodyCreationSettings body_settings( compound_shape.Get(), {transform.position.x, transform.position.y, transform.position.z}, {rotation.x, rotation.y, rotation.z, rotation.w}, static_cast<JPH::EMotionType>(component.type), layer_index ); JPH::MassProperties mass_properties; mass_properties.mMass = glm::max(0.01f, component.mass); body_settings.mMassPropertiesOverride = mass_properties; body_settings.mOverrideMassProperties = JPH::EOverrideMassProperties::CalculateInertia; body_settings.mAllowSleeping = component.allow_sleep; body_settings.mLinearDamping = glm::max(0.0f, component.linear_drag); body_settings.mAngularDamping = glm::max(0.0f, component.angular_drag); body_settings.mMotionQuality = component.continuous ? JPH::EMotionQuality::LinearCast : JPH::EMotionQuality::Discrete; body_settings.mGravityFactor = component.gravity_factor; body_settings.mAllowedDOFs = static_cast<JPH::EAllowedDOFs>(component.allowed_dofs); body_settings.mFriction = component.friction; body_settings.mRestitution = component.restitution; body_settings.mIsSensor = component.is_sensor; JPH::Body* body = body_interface.CreateBody(body_settings); OX_CHECK_NULL(body, "Jolt is out of bodies!"); JPH::EActivation activation = component.awake && component.type != RigidBodyComponent::BodyType::Static ? JPH::EActivation::Activate : JPH::EActivation::DontActivate; body_interface.AddBody(body->GetID(), activation); body->SetUserData(static_cast<u64>(entity.id())); component.runtime_body = body; } void Scene::create_character_controller( flecs::entity entity, const TransformComponent& transform, CharacterControllerComponent& component ) const { ZoneScoped; auto& physics = App::mod<Physics>(); const auto position = JPH::Vec3(transform.position.x, transform.position.y, transform.position.z); const auto capsule_shape = JPH::RotatedTranslatedShapeSettings( JPH::Vec3(0, 0.5f * component.character_height_standing + component.character_radius_standing, 0), JPH::Quat::sIdentity(), new JPH::CapsuleShape(0.5f * component.character_height_standing, component.character_radius_standing) ) .Create() .Get(); // Create character const std::shared_ptr<JPH::CharacterSettings> settings = std::make_shared<JPH::CharacterSettings>(); settings->mMaxSlopeAngle = JPH::DegreesToRadians(45.0f); settings->mLayer = PhysicsLayers::MOVING; settings->mShape = capsule_shape; settings->mFriction = 0.0f; // For now this is not set. settings->mSupportingVolume = JPH::Plane( JPH::Vec3::sAxisY(), -component.character_radius_standing ); // Accept contacts that touch the // lower sphere of the capsule component .character = new JPH::Character(settings.get(), position, JPH::Quat::sIdentity(), 0, physics.get_physics_system()); auto* ch = reinterpret_cast<JPH::Character*>(component.character); ch->AddToPhysicsSystem(JPH::EActivation::Activate); auto ch_body = physics.get_body_interface_lock().TryGetBody(ch->GetBodyID()); ch_body->SetUserData(static_cast<u64>(entity.id())); } auto Scene::save_to_file(this const Scene& self, std::string path) -> bool { ZoneScoped; JsonWriter writer{}; writer.begin_obj(); writer["name"] = self.scene_name; writer["scripts"].begin_array(); for (auto& [uuid, system] : self.lua_systems) { writer.begin_obj(); writer["uuid"] = uuid.str(); writer.end_obj(); } writer.end_array(); writer["entities"].begin_array(); const auto q = self.world.query_builder().with<TransformComponent>().build(); q.each([&writer](flecs::entity e) { if (e.parent() == flecs::entity::null() && !e.has<Hidden>()) { entity_to_json(writer, e); } }); writer.end_array(); writer.end_obj(); std::ofstream filestream(path); filestream << writer.stream.rdbuf(); OX_LOG_INFO("Saved scene {0}.", self.scene_name); return true; } auto Scene::load_from_file(this Scene& self, const std::string& path) -> bool { ZoneScoped; namespace sj = simdjson; std::string content = fs::read_file(path); if (content.empty()) { OX_LOG_ERROR("Failed to read/open file {}!", path); return false; } content = sj::padded_string(content); sj::ondemand::parser parser; auto doc = parser.iterate(content); if (doc.error()) { OX_LOG_ERROR("Failed to parse scene file! {}", sj::error_message(doc.error())); return false; } auto name_json = doc["name"]; if (name_json.error()) { OX_LOG_ERROR("Scene files must have names!"); return false; } self.scene_name = name_json.get_string().value_unsafe(); std::vector<UUID> requested_assets = {}; auto scripts_array = doc["scripts"]; for (auto script_json : scripts_array.get_array()) { auto uuid_json = script_json.value_unsafe(); auto uuid_str = uuid_json["uuid"].get_string(); if (!uuid_str.error()) { auto script_uuid = UUID::from_string(uuid_str.value_unsafe()).value(); requested_assets.emplace_back(script_uuid); } } auto entities_array = doc["entities"]; for (auto entity_json : entities_array.get_array()) { if (!json_to_entity(self, flecs::entity::null(), entity_json.value_unsafe(), requested_assets).second) { return false; } } OX_LOG_TRACE("Loading scene {} with {} assets...", self.scene_name, requested_assets.size()); for (const auto& uuid : requested_assets) { auto& asset_man = App::mod<AssetManager>(); if (auto asset = asset_man.get_asset(uuid); asset) { if (asset->type == AssetType::Script) { self.add_lua_system(uuid); } else { asset_man.load_asset(uuid); } } } return true; } } // namespace ox
0
0.902057
1
0.902057
game-dev
MEDIA
0.841145
game-dev
0.886142
1
0.886142
Legacy-Fabric/fabric
1,720
legacy-fabric-command-api-v2/1.7.10/src/main/java/net/legacyfabric/fabric/impl/command/ImplInit.java
/* * Copyright (c) 2020 - 2025 Legacy Fabric * Copyright (c) 2016 - 2022 FabricMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.legacyfabric.fabric.impl.command; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.DedicatedServerModInitializer; import net.legacyfabric.fabric.api.command.v2.CommandRegistrar; import net.legacyfabric.fabric.api.command.v2.lib.sponge.CommandManager; import net.legacyfabric.fabric.api.registry.CommandRegistrationCallback; public class ImplInit implements DedicatedServerModInitializer, ClientModInitializer, CommandRegistrar { @Override public void register(CommandManager manager, boolean dedicated) { CommandRegistrationCallback.EVENT.register(registry -> { CommandRegistrar.EVENT.invoker().register(manager, dedicated); InternalObjects.getCommandManager().getCommands().forEach(mapping -> { CommandWrapper wrapper = new CommandWrapper(mapping); registry.register(wrapper); }); }); } @Override public void onInitializeClient() { this.register(InternalObjects.getCommandManager(), false); } @Override public void onInitializeServer() { this.register(InternalObjects.getCommandManager(), true); } }
0
0.869814
1
0.869814
game-dev
MEDIA
0.731015
game-dev
0.531836
1
0.531836
Elfansoer/dota-2-lua-abilities
2,344
scripts/vscripts/lua_abilities/ogre_magi_fireblast_lua/ogre_magi_fireblast_lua.lua
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- ogre_magi_fireblast_lua = class({}) LinkLuaModifier( "modifier_generic_stunned_lua", "lua_abilities/generic/modifier_generic_stunned_lua", LUA_MODIFIER_MOTION_NONE ) -------------------------------------------------------------------------------- -- Ability Start function ogre_magi_fireblast_lua:OnSpellStart() -- unit identifier local caster = self:GetCaster() local target = self:GetCursorTarget() -- cancel if linken if target:TriggerSpellAbsorb( self ) then return end -- load data local duration = self:GetSpecialValueFor( "stun_duration" ) local damage = self:GetSpecialValueFor( "fireblast_damage" ) -- Apply damage local damageTable = { victim = target, attacker = caster, damage = damage, damage_type = self:GetAbilityDamageType(), ability = self, --Optional. } ApplyDamage( damageTable ) -- stun target:AddNewModifier( self:GetCaster(), self, "modifier_generic_stunned_lua", {duration = duration} ) -- play effects self:PlayEffects( target ) end -------------------------------------------------------------------------------- function ogre_magi_fireblast_lua:PlayEffects( target ) -- Get Resources local particle_cast = "particles/units/heroes/hero_ogre_magi/ogre_magi_fireblast.vpcf" local sound_cast = "Hero_OgreMagi.Fireblast.Cast" local sound_target = "Hero_OgreMagi.Fireblast.Target" -- Create Particle -- local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, target ) local effect_cast = assert(loadfile("lua_abilities/rubick_spell_steal_lua/rubick_spell_steal_lua_arcana"))(self, particle_cast, PATTACH_ABSORIGIN_FOLLOW, target ) ParticleManager:SetParticleControlEnt( effect_cast, 0, target, PATTACH_POINT_FOLLOW, "attach_hitloc", Vector(0,0,0), -- unknown true -- unknown, true ) ParticleManager:SetParticleControl( effect_cast, 1, target:GetOrigin() ) ParticleManager:ReleaseParticleIndex( effect_cast ) -- Create Sound EmitSoundOn( sound_cast, self:GetCaster() ) EmitSoundOn( sound_target, target ) end
0
0.923754
1
0.923754
game-dev
MEDIA
0.996087
game-dev
0.959039
1
0.959039
awgil/ffxiv_bossmod
2,017
BossMod/Modules/Shadowbringers/Foray/Duel/Duel5Menenius/GunberdShot.cs
namespace BossMod.Shadowbringers.Foray.Duel.Duel5Menenius; class GunberdShot(BossModule module) : BossComponent(module) { private Actor? _gunberdCaster; public bool DarkShotLoaded { get; private set; } public bool WindslicerLoaded { get; private set; } public bool Gunberding { get; private set; } public override void AddGlobalHints(GlobalHints hints) { if (Gunberding) { if (DarkShotLoaded) hints.Add("Maintain Distance"); if (WindslicerLoaded) hints.Add("Knockback"); } else { if (DarkShotLoaded) hints.Add("Dark Loaded"); if (WindslicerLoaded) hints.Add("Windslicer Loaded"); } } public override void OnCastStarted(Actor caster, ActorCastInfo spell) { switch ((AID)spell.Action.ID) { case AID.DarkShot: DarkShotLoaded = true; break; case AID.WindslicerShot: WindslicerLoaded = true; break; case AID.GunberdDark: case AID.GunberdWindslicer: Gunberding = true; _gunberdCaster = caster; break; } } public override void OnCastFinished(Actor caster, ActorCastInfo spell) { switch ((AID)spell.Action.ID) { case AID.GunberdDark: DarkShotLoaded = false; Gunberding = false; break; case AID.GunberdWindslicer: WindslicerLoaded = false; Gunberding = false; break; } } public override void DrawArenaForeground(int pcSlot, Actor pc) { if (Gunberding && WindslicerLoaded) { var adjPos = Components.Knockback.AwayFromSource(pc.Position, _gunberdCaster, 10); Components.Knockback.DrawKnockback(pc, adjPos, Arena); } } }
0
0.800135
1
0.800135
game-dev
MEDIA
0.961786
game-dev
0.757312
1
0.757312
ReksioEngine/ReksioEngine
2,989
src/devPlayer.ts
import { BUILD_VARS, createGamePlayer, GamePlayerOptions } from './index' import { ArchiveOrgFileLoader, ListingJSONUrlFileLoader, GithubFileLoader, IsoFileLoader, RemoteIsoFileLoader, } from './filesystem/fileLoader' import { SaveFileManager } from './engine/saveFile' import { IndexedDBStorage } from './filesystem/fileStorage' const urlParams = new URLSearchParams(window.location.search) const gameContainer = document.getElementById('game')! const debugContainer = document.getElementById('debug') const controls = document.getElementById('controls')! const savesEnabledEntry: string | null = localStorage.getItem('savesEnabled') const areSavesEnabled = savesEnabledEntry == 'true' || savesEnabledEntry === null const baseOptions = { startScene: urlParams.get('scene') ?? undefined, debug: urlParams.has('debug') ? urlParams.get('debug') == 'true' : BUILD_VARS.debug, debugContainer: debugContainer, onExit: () => document.exitFullscreen(), saveFile: areSavesEnabled ? SaveFileManager.fromLocalStorage() : undefined, storage: new IndexedDBStorage('reksio') } let config = {} const start = () => { gameContainer.removeEventListener('click', start) gameContainer.classList.remove('notready') const player = createGamePlayer(gameContainer, config as GamePlayerOptions) if (player) { void player.start() } } if (urlParams.get('loader') === 'iso-local') { const fileSelector = document.createElement('input') fileSelector.type = 'file' fileSelector.addEventListener('change', (event: any) => { controls.removeChild(fileSelector) config = { ...baseOptions, fileLoader: new IsoFileLoader(event.target.files[0]), } gameContainer.classList.add('notready') gameContainer.addEventListener('click', start) }) controls.appendChild(fileSelector) } else { const getFileLoader = () => { const loader = urlParams.get('loader') const source = urlParams.get('source') if (loader && source) { if (loader === 'github') { return new GithubFileLoader(source) } else if (loader === 'archiveorg') { return new ArchiveOrgFileLoader(source) } else if (loader === 'listingjson') { return new ListingJSONUrlFileLoader(source) } else if (loader === 'iso-remote') { return new RemoteIsoFileLoader(source) } } return new ListingJSONUrlFileLoader('https://iso.zagrajwreksia.pl/game-assets/reksioiskarbpiratow/listing.json') } config = { ...baseOptions, fileLoader: getFileLoader(), } gameContainer!.classList.add('notready') gameContainer!.addEventListener('click', start) } const enterFullscreen = document.querySelector('#enterFullscreen')! enterFullscreen.addEventListener('click', async () => { await gameContainer!.requestFullscreen() })
0
0.8802
1
0.8802
game-dev
MEDIA
0.395496
game-dev
0.94164
1
0.94164
IJEMIN/Unity-Programming-Essence-2021
1,443
18/Zombie Multiplayer/Assets/Photon/PhotonUnityNetworking/Demos/PunCockpit/Scripts/ReadOnlyProperties/CurrentRoomPropertiesListedInLobbyProperty.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RoomListView.cs" company="Exit Games GmbH"> // Part of: Pun Cockpit // </copyright> // <author>developer@exitgames.com</author> // -------------------------------------------------------------------------------------------------------------------- using UnityEngine.UI; using System.Linq; namespace Photon.Pun.Demo.Cockpit { /// <summary> /// PhotonNetwork.CurrentRoom.PropertiesListedInLobby UI property. /// </summary> public class CurrentRoomPropertiesListedInLobbyProperty : PropertyListenerBase { public Text Text; string[] _cache = null; void Update() { if (PhotonNetwork.CurrentRoom != null) { if (_cache == null || !PhotonNetwork.CurrentRoom.PropertiesListedInLobby.SequenceEqual(_cache)) { _cache = PhotonNetwork.CurrentRoom.PropertiesListedInLobby.Clone() as string[]; Text.text = string.Join("\n", PhotonNetwork.CurrentRoom.PropertiesListedInLobby); this.OnValueChanged(); } } else { if (_cache != null) { _cache = null; Text.text = "n/a"; } } } } }
0
0.788162
1
0.788162
game-dev
MEDIA
0.699643
game-dev
0.906318
1
0.906318
RigsOfRods/rigs-of-rods
1,832
source/main/gameplay/RaceSystem.cpp
/* This source file is part of Rigs of Rods Copyright 2005-2012 Pierre-Michel Ricordel Copyright 2007-2012 Thomas Fischer Copyright 2015-2020 Petr Ohlidal For more information, see http://www.rigsofrods.org/ Rigs of Rods is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. Rigs of Rods 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 Rigs of Rods. If not, see <http://www.gnu.org/licenses/>. */ /// Counterpart to Neorej16's race system script #include "RaceSystem.h" #include "AppContext.h" #include "GameContext.h" using namespace RoR; void RaceSystem::UpdateDirectionArrow(char* text, Ogre::Vector3 position) { if (text == nullptr) { m_dir_arrow_visible = false; m_dir_arrow_target = Ogre::Vector3::ZERO; } else { m_dir_arrow_visible = true; m_dir_arrow_text = text; m_dir_arrow_target = position; } } void RaceSystem::StartRaceTimer(int id) { m_race_start_time = App::GetGameContext()->GetActorManager()->GetTotalTime(); m_race_time_diff = 0.0f; m_race_id = id; } void RaceSystem::StopRaceTimer() { m_race_start_time = 0.0f; m_race_id = -1; } float RaceSystem::GetRaceTime() const { return App::GetGameContext()->GetActorManager()->GetTotalTime() - m_race_start_time; } void RaceSystem::ResetRaceUI() { this->StopRaceTimer(); this->UpdateDirectionArrow(nullptr, Ogre::Vector3::ZERO); // hide arrow }
0
0.750345
1
0.750345
game-dev
MEDIA
0.679578
game-dev
0.781616
1
0.781616
thedarkcolour/ForestryCE
19,116
src/main/java/forestry/mail/carriers/trading/TradeStation.java
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.mail.carriers.trading; import com.mojang.authlib.GameProfile; import forestry.api.mail.*; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.InventoryUtil; import forestry.core.utils.ItemStackUtil; import forestry.mail.*; import forestry.mail.carriers.PostalCarriers; import forestry.mail.features.MailItems; import forestry.mail.inventory.InventoryTradeStation; import forestry.mail.items.EnumStampDefinition; import forestry.mail.postalstates.EnumDeliveryState; import forestry.mail.postalstates.ResponseNotMailable; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import javax.annotation.Nullable; import java.util.HashSet; import java.util.List; import java.util.Set; public class TradeStation implements ITradeStation { public static final short SLOT_TRADEGOOD = 0; public static final short SLOT_TRADEGOOD_COUNT = 1; public static final short SLOT_EXCHANGE_1 = 1; public static final short SLOT_EXCHANGE_COUNT = 4; public static final short SLOT_LETTERS_1 = 5; public static final short SLOT_LETTERS_COUNT = 6; public static final short SLOT_STAMPS_1 = 11; public static final short SLOT_STAMPS_COUNT = 4; public static final short SLOT_RECEIVE_BUFFER = 15; public static final short SLOT_RECEIVE_BUFFER_COUNT = 15; public static final short SLOT_SEND_BUFFER = 30; public static final short SLOT_SEND_BUFFER_COUNT = 10; public static final int SLOT_SIZE = SLOT_TRADEGOOD_COUNT + SLOT_EXCHANGE_COUNT + SLOT_LETTERS_COUNT + SLOT_STAMPS_COUNT + SLOT_RECEIVE_BUFFER_COUNT + SLOT_SEND_BUFFER_COUNT; @Nullable private GameProfile owner; @Nullable private IMailAddress address; private boolean isVirtual = false; private boolean isInvalid = false; private final InventoryAdapter inventory = new InventoryTradeStation(); private final Set<Watcher> updateWatchers = new HashSet<>(); public TradeStation(@Nullable GameProfile owner, IMailAddress address) { if (!address.getCarrier().equals(PostalCarriers.TRADER.get())) { throw new IllegalArgumentException("TradeStation address must be a trader"); } this.owner = owner; this.address = address; } public TradeStation(CompoundTag tag) { read(tag); } @Override public @Nullable IMailAddress getAddress() { return this.address; } // / SAVING & LOADING public CompoundTag save(CompoundTag compoundNBT) { if (this.owner != null) { CompoundTag nbt = new CompoundTag(); NbtUtils.writeGameProfile(nbt, this.owner); compoundNBT.put("owner", nbt); } if (this.address != null) { CompoundTag nbt = new CompoundTag(); this.address.write(nbt); compoundNBT.put("address", nbt); } compoundNBT.putBoolean("VRT", this.isVirtual); compoundNBT.putBoolean("IVL", this.isInvalid); this.inventory.write(compoundNBT); return compoundNBT; } @Override public CompoundTag write(CompoundTag nbt) { return save(nbt); } @Override public void read(CompoundTag nbt) { if (nbt.contains("owner")) { this.owner = NbtUtils.readGameProfile(nbt.getCompound("owner")); } if (nbt.contains("address")) { this.address = new MailAddress(nbt.getCompound("address")); } this.isVirtual = nbt.getBoolean("VRT"); this.isInvalid = nbt.getBoolean("IVL"); this.inventory.read(nbt); } /* INVALIDATING */ @Override public boolean isValid() { return !this.isInvalid || this.address == null; } @Override public void invalidate() { this.isInvalid = true; } /* INFORMATION */ @Override public void setVirtual(boolean isVirtual) { this.isVirtual = isVirtual; setDirty(); } @Override public boolean isVirtual() { return this.isVirtual; } @Override public TradeStationInfo getTradeInfo() { List<ItemStack> condensedRequired = ItemStackUtil.condenseStacks(InventoryUtil.getStacks(this.inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); // Set current state EnumTradeStationState state = EnumTradeStationState.OK; // Virtual trade stations are always ready for service. if (!isVirtual()) { // Will assume that the owner should get a notice. if (!hasPaper(2)) { state = EnumTradeStationState.INSUFFICIENT_PAPER; } if (!canPayPostage(3)) { state = EnumTradeStationState.INSUFFICIENT_STAMPS; } if (countFillableOrders(1, this.inventory.getItem(SLOT_TRADEGOOD)) <= 0) { state = EnumTradeStationState.INSUFFICIENT_TRADE_GOOD; } } return new TradeStationInfo(this.address, this.owner, this.inventory.getItem(SLOT_TRADEGOOD), condensedRequired, state); } /* ILETTERHANDLER */ @Override public IPostalState handleLetter(ServerLevel world, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { boolean sendOwnerNotice = doLodge && this.owner != null; ILetter letter = LetterUtils.getLetter(letterstack); if (!isVirtual() && !hasPaper(sendOwnerNotice ? 2 : 1)) { return EnumTradeStationState.INSUFFICIENT_PAPER; } int ordersToFillCount = ItemStackUtil.containsSets(InventoryUtil.getStacks(this.inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT), letter.getAttachments()); // Not a single match. if (ordersToFillCount <= 0) { return EnumTradeStationState.INSUFFICIENT_OFFER; } if (!isVirtual()) { int fillable = countFillableOrders(ordersToFillCount, this.inventory.getItem(SLOT_TRADEGOOD)); // Nothing can be filled. if (fillable <= 0) { return EnumTradeStationState.INSUFFICIENT_TRADE_GOOD; } if (fillable < ordersToFillCount) { ordersToFillCount = fillable; } // Check for sufficient output buffer int storable = countStorablePayment(ordersToFillCount, InventoryUtil.getStacks(this.inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); if (storable <= 0) { return EnumTradeStationState.INSUFFICIENT_BUFFER; } if (storable < ordersToFillCount) { ordersToFillCount = storable; } } // Prepare the letter ILetter mail = new Letter(this.address, letter.getSender()); mail.setText(Component.translatable("for.gui.mail.order.attached").getString()); for (int i = 0; i < ordersToFillCount; i++) { mail.addAttachment(this.inventory.getItem(SLOT_TRADEGOOD).copy()); } mail.addAttachments(getSurplusAttachments(ordersToFillCount, letter.getAttachments())); // Check for necessary postage int requiredPostage = mail.requiredPostage(); if (!isVirtual()) { if (!canPayPostage(requiredPostage + (sendOwnerNotice ? 1 : 0))) { return EnumTradeStationState.INSUFFICIENT_STAMPS; } } // Attach necessary postage int[] stampCount = getPostage(requiredPostage, isVirtual()); for (int i = 0; i < stampCount.length; i++) { int count = stampCount[i]; if (count > 0) { EnumPostage postage = EnumPostage.values()[i]; EnumStampDefinition stampDefinition = EnumStampDefinition.getFromPostage(postage); mail.addStamps(MailItems.STAMPS.stack(stampDefinition, count)); } } // Send the letter CompoundTag compoundNBT = new CompoundTag(); mail.write(compoundNBT); ItemStack mailstack = LetterProperties.createStampedLetterStack(mail); mailstack.setTag(compoundNBT); IPostalState responseState = PostOffice.getOrCreate(world).lodgeLetter(world, mailstack, doLodge); if (!responseState.isOk()) { return new ResponseNotMailable(responseState); } // Store received items for (int i = 0; i < ordersToFillCount; i++) { for (ItemStack stack : InventoryUtil.getStacks(this.inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)) { if (stack == null) { continue; } InventoryUtil.tryAddStack(this.inventory, stack.copy(), SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, false); } } // Remove resources removePaper(); removeStamps(stampCount); removeTradegood(ordersToFillCount); // Send confirmation message to seller if (sendOwnerNotice) { compoundNBT = new CompoundTag(); ILetter confirm = new Letter(this.address, new MailAddress(this.owner)); String orderFilledMessage; if (ordersToFillCount == 1) { orderFilledMessage = Component.translatable("for.gui.mail.order.filled.one").getString(); } else { orderFilledMessage = Component.translatable("for.gui.mail.order.filled.multiple").getString(); orderFilledMessage = orderFilledMessage.replace("%COUNT", Integer.toString(ordersToFillCount)); } orderFilledMessage = orderFilledMessage.replace("%SENDER", letter.getSender().getName()); confirm.setText(orderFilledMessage); confirm.addStamps(MailItems.STAMPS.stack(EnumStampDefinition.P_1, 1)); confirm.write(compoundNBT); ItemStack confirmstack = LetterProperties.createStampedLetterStack(confirm); confirmstack.setTag(compoundNBT); PostOffice.getOrCreate(world).lodgeLetter(world, confirmstack, doLodge); removePaper(); removeStamps(new int[]{0, 1}); } setDirty(); return EnumDeliveryState.OK; } /* TRADE LOGIC */ private int countFillableOrders(int max, ItemStack tradegood) { if (tradegood.isEmpty()) { return 0; } // How many orders are fillable? float orderCount = 0; for (ItemStack stack : InventoryUtil.getStacks(this.inventory, SLOT_SEND_BUFFER, SLOT_SEND_BUFFER_COUNT)) { if (stack != null && ItemStack.isSameItemSameTags(stack, tradegood)) { orderCount += stack.getCount() / (float) tradegood.getCount(); if (orderCount >= max) { return max; } } } return (int) Math.floor(orderCount); } public boolean canReceivePayment() { InventoryAdapter test = this.inventory.copy(); NonNullList<ItemStack> payment = InventoryUtil.getStacks(this.inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); return InventoryUtil.tryAddStacksCopy(test, payment, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true); } private int countStorablePayment(int max, NonNullList<ItemStack> exchange) { InventoryAdapter test = this.inventory.copy(); int count = 0; for (int i = 0; i < max; i++) { if (InventoryUtil.tryAddStacksCopy(test, exchange, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true)) { count++; } else { break; } } return count; } private void removeTradegood(int filled) { for (int j = 0; j < filled; j++) { int toRemove = this.inventory.getItem(SLOT_TRADEGOOD).getCount(); for (int i = SLOT_SEND_BUFFER; i < SLOT_SEND_BUFFER + SLOT_SEND_BUFFER_COUNT; i++) { ItemStack buffer = this.inventory.getItem(i); if (!buffer.isEmpty() && ItemStack.isSameItemSameTags(buffer, this.inventory.getItem(SLOT_TRADEGOOD))) { ItemStack decrease = this.inventory.removeItem(i, toRemove); toRemove -= decrease.getCount(); if (toRemove <= 0) { break; } } } } } // Checks if this trade station has enough paper. private boolean hasPaper(int amountRequired) { int amountFound = 0; for (ItemStack stack : InventoryUtil.getStacks(this.inventory, SLOT_LETTERS_1, SLOT_LETTERS_COUNT)) { if (stack != null) { amountFound += stack.getCount(); } if (amountFound >= amountRequired) { return true; } } return false; } // Removes a single paper from the inventory private void removePaper() { for (int i = SLOT_LETTERS_1; i < SLOT_LETTERS_1 + SLOT_LETTERS_COUNT; i++) { ItemStack stack = this.inventory.getItem(i); if (stack.getItem() == Items.PAPER) { this.inventory.removeItem(i, 1); break; } } } private boolean canPayPostage(int postage) { int posted = 0; for (ItemStack stamp : InventoryUtil.getStacks(this.inventory, SLOT_STAMPS_1, SLOT_STAMPS_COUNT)) { if (stamp == null) { continue; } if (!(stamp.getItem() instanceof IStamps)) { continue; } posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); if (posted >= postage) { return true; } } return false; } private int[] getPostage(final int postageRequired, boolean virtual) { int[] stamps = new int[EnumPostage.values().length]; int postageRemaining = postageRequired; for (int i = EnumPostage.values().length - 1; i > 0; i--) { if (postageRemaining <= 0) { break; } EnumPostage postValue = EnumPostage.values()[i]; if (postValue.getValue() > postageRemaining) { continue; } int num = virtual ? 99 : getNumStamps(postValue); int max = (int) Math.floor(postageRemaining / postValue.getValue()); if (max < num) { num = max; } stamps[i] = num; postageRemaining -= num * postValue.getValue(); } // use larger stamps if exact change isn't available if (postageRemaining > 0) { for (int i = 0; i < EnumPostage.values().length; i++) { EnumPostage postValue = EnumPostage.values()[i]; if (postValue.getValue() >= postageRequired) { stamps = new int[EnumPostage.values().length]; int num = virtual ? 99 : getNumStamps(postValue); if (num > 0) { stamps[i] = 1; return stamps; } } } } // if there isn't a single larger stamp we will just combine smaller ones, starting with the higher values // this is totally disregarding whether there's a better solution or not, but I won't implement a knapsack solver here if (postageRemaining > 0) { postageRemaining = postageRequired; stamps = new int[EnumPostage.values().length]; for (int i = stamps.length - 1; i >= 0; i--) { EnumPostage postValue = EnumPostage.values()[i]; int num = virtual ? 99 : getNumStamps(postValue); int reqNum = Math.min((int) Math.ceil((double) postageRemaining / postValue.getValue()), num); stamps[i] = reqNum; postageRemaining -= reqNum * postValue.getValue(); if (postageRemaining <= 0) { return stamps; } } } return stamps; } private int getNumStamps(EnumPostage postage) { int count = 0; for (ItemStack stamp : InventoryUtil.getStacks(this.inventory, SLOT_STAMPS_1, SLOT_STAMPS_COUNT)) { if (stamp == null) { continue; } if (!(stamp.getItem() instanceof IStamps)) { continue; } if (((IStamps) stamp.getItem()).getPostage(stamp) == postage) { count += stamp.getCount(); } } return count; } private void removeStamps(int[] stampCount) { for (int i = 1; i < stampCount.length; i++) { if (stampCount[i] <= 0) { continue; } for (int j = SLOT_STAMPS_1; j < SLOT_STAMPS_1 + SLOT_STAMPS_COUNT; j++) { if (stampCount[i] <= 0) { continue; } ItemStack stamp = this.inventory.getItem(j); if (stamp.isEmpty()) { continue; } if (!(stamp.getItem() instanceof IStamps)) { continue; } if (((IStamps) stamp.getItem()).getPostage(stamp) == EnumPostage.values()[i]) { ItemStack decrease = this.inventory.removeItem(j, stampCount[i]); stampCount[i] -= decrease.getCount(); } } } } private NonNullList<ItemStack> getSurplusAttachments(int filled, NonNullList<ItemStack> attachments) { NonNullList<ItemStack> surplus = NonNullList.create(); // Get a copy of the attachments to play with NonNullList<ItemStack> pool = NonNullList.withSize(attachments.size(), ItemStack.EMPTY); for (int i = 0; i < attachments.size(); i++) { ItemStack attachment = attachments.get(i); if (!attachment.isEmpty()) { pool.set(i, attachment.copy()); } } // Remove stuff until we are only left with the remnants for (int i = 0; i < filled; i++) { NonNullList<ItemStack> required = InventoryUtil.getStacks(this.inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); List<ItemStack> condensedRequired = ItemStackUtil.condenseStacks(required); for (ItemStack req : condensedRequired) { for (int j = 0; j < pool.size(); j++) { ItemStack pol = pool.get(j); if (pol.isEmpty()) { continue; } if (!ItemStack.isSameItem(pol, req)) { continue; } if (req.getCount() >= pol.getCount()) { req.shrink(pol.getCount()); pool.set(j, ItemStack.EMPTY); } else { pol.shrink(req.getCount()); req.setCount(0); } } } } for (ItemStack stack : pool) { if (stack != null) { surplus.add(stack); } } return surplus; } /* IINVENTORY */ @Override public boolean isEmpty() { return this.inventory.isEmpty(); } public void setDirty() { this.updateWatchers.forEach(Watcher::onWatchableUpdate); this.inventory.setChanged(); } @Override public void setItem(int slot, ItemStack itemStack) { this.setDirty(); this.inventory.setItem(slot, itemStack); } @Override public int getContainerSize() { return this.inventory.getContainerSize(); } @Override public ItemStack getItem(int var1) { return this.inventory.getItem(var1); } @Override public ItemStack removeItem(int var1, int var2) { return this.inventory.removeItem(var1, var2); } @Override public ItemStack removeItemNoUpdate(int index) { return this.inventory.removeItemNoUpdate(index); } @Override public int getMaxStackSize() { return this.inventory.getMaxStackSize(); } @Override public void setChanged() { } @Override public boolean stillValid(Player player) { return true; } @Override public void startOpen(Player player) { } @Override public void stopOpen(Player player) { } @Override public boolean canPlaceItem(int i, ItemStack itemStack) { return this.inventory.canPlaceItem(i, itemStack); } @Override public int[] getSlotsForFace(Direction side) { return this.inventory.getSlotsForFace(side); } @Override public boolean canPlaceItemThroughFace(int slot, ItemStack itemStack, Direction side) { return this.inventory.canPlaceItemThroughFace(slot, itemStack, side); } @Override public boolean canTakeItemThroughFace(int slot, ItemStack itemStack, Direction side) { return this.inventory.canTakeItemThroughFace(slot, itemStack, side); } @Override public boolean canSlotAccept(int slotIndex, ItemStack stack) { return this.inventory.canSlotAccept(slotIndex, stack); } @Override public boolean isLocked(int slotIndex) { return this.inventory.isLocked(slotIndex); } @Override public void clearContent() { } public boolean registerUpdateWatcher(Watcher updateWatcher) { return this.updateWatchers.add(updateWatcher); } public boolean unregisterUpdateWatcher(Watcher updateWatcher) { return this.updateWatchers.remove(updateWatcher); } }
0
0.876667
1
0.876667
game-dev
MEDIA
0.820439
game-dev,distributed-systems
0.794978
1
0.794978
MCreator/MCreator
6,310
src/main/java/net/mcreator/element/converter/v2024_3/EnchantmentDefinitionConverter.java
/* * MCreator (https://mcreator.net/) * Copyright (C) 2012-2020, Pylo * Copyright (C) 2020-2024, Pylo, opensource contributors * * 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 net.mcreator.element.converter.v2024_3; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.mcreator.element.GeneratableElement; import net.mcreator.element.converter.IConverter; import net.mcreator.element.parts.MItemBlock; import net.mcreator.element.types.Enchantment; import net.mcreator.minecraft.DataListEntry; import net.mcreator.minecraft.ElementUtil; import net.mcreator.workspace.Workspace; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class EnchantmentDefinitionConverter implements IConverter { private static final Gson gson = new GsonBuilder().create(); @Override public GeneratableElement convert(Workspace workspace, GeneratableElement input, JsonElement jsonElementInput) { Enchantment enchantment = (Enchantment) input; JsonObject definition = jsonElementInput.getAsJsonObject().getAsJsonObject("definition"); String type = definition.get("type").getAsString(); enchantment.supportedSlots = switch (type) { case "ARMOR_FEET" -> "feet"; case "ARMOR_LEGS" -> "legs"; case "ARMOR_CHEST" -> "chest"; case "ARMOR_HEAD" -> "head"; case "ARMOR", "WEARABLE" -> "armor"; case "SWORD", "FIRE_ASPECT", "SHARP", "WEAPON", "DIGGER", "DIGGER_LOOT", "FISHING_ROD", "TRIDENT", "BOW", "CROSSBOW", "MACE" -> "mainhand"; default -> "any"; }; String rarity = definition.get("rarity").getAsString(); enchantment.weight = switch (rarity) { case "UNCOMMON" -> 5; case "RARE" -> 2; case "VERY_RARE" -> 1; default -> 10; }; enchantment.anvilCost = switch (rarity) { case "UNCOMMON" -> 2; case "RARE" -> 4; case "VERY_RARE" -> 8; default -> 1; }; List<net.mcreator.element.parts.Enchantment> compatibleEnchantments = definition.has("compatibleEnchantments") ? Arrays.asList(gson.fromJson(definition.get("compatibleEnchantments"), net.mcreator.element.parts.Enchantment[].class)) : new ArrayList<>(); boolean excludeEnchantments = definition.has("excludeEnchantments") && definition.get("excludeEnchantments").getAsBoolean(); enchantment.incompatibleEnchantments = new ArrayList<>(); if (!compatibleEnchantments.isEmpty()) { // if empty, it is compatible with all enchantments thus we leave enchantment.incompatibleEnchantments empty if (excludeEnchantments) { // incompatibleEnchantments works in exclude mode - directly convert for (net.mcreator.element.parts.Enchantment compatibleEnchantment : compatibleEnchantments) { // should not be possible to have tags here in FV<69, but just in case if (!compatibleEnchantment.getUnmappedValue().startsWith("#")) { compatibleEnchantment.setWorkspace(workspace); enchantment.incompatibleEnchantments.add(compatibleEnchantment); } } } else { // if list was in include mode, we need to exclude all but those listed here as a workaround List<DataListEntry> allEnchantments = ElementUtil.loadAllEnchantments(workspace); for (DataListEntry entry : allEnchantments) { net.mcreator.element.parts.Enchantment enchantmentEntry = new net.mcreator.element.parts.Enchantment( workspace, entry); // If in include mode and compatibleEnchantments does not contain the entry, add it to incompatibleEnchantments // Also make sure to not add this enchantment itself to incompatibleEnchantments if (!compatibleEnchantments.contains(enchantmentEntry) && !enchantmentEntry.getUnmappedValue() .equals("CUSTOM:" + enchantment.getModElement().getName())) { enchantment.incompatibleEnchantments.add(enchantmentEntry); } } } } List<MItemBlock> compatibleItems = definition.has("compatibleItems") ? Arrays.asList(gson.fromJson(definition.get("compatibleItems"), MItemBlock[].class)) : new ArrayList<>(); boolean excludeItems = definition.has("excludeItems") && definition.get("excludeItems").getAsBoolean(); enchantment.supportedItems = new ArrayList<>(); if (!compatibleItems.isEmpty() && !excludeItems) { // include mode with non-empty compatibleItems list, we can convert directly for (MItemBlock compatibleItem : compatibleItems) { // we do not allow tags in enchantment.supportedItems, unless there is only one item (tag) in the list if (!compatibleItem.getUnmappedValue().startsWith("TAG:") || compatibleItems.size() == 1) { compatibleItem.setWorkspace(workspace); enchantment.supportedItems.add(compatibleItem); } } } // If at this point, supportedItems is empty, we need to find suitable fallback if (enchantment.supportedItems.isEmpty()) { enchantment.supportedItems.add(new MItemBlock(workspace, "TAG:enchantable/" + switch (type) { case "ARMOR_FEET" -> "foot_armor"; case "ARMOR_LEGS" -> "leg_armor"; case "ARMOR_CHEST" -> "chest_armor"; case "ARMOR_HEAD" -> "head_armor"; case "ARMOR" -> "armor"; case "SWORD" -> "sword"; case "FIRE_ASPECT" -> "fire_aspect"; case "SHARP" -> "sharp_weapon"; case "WEAPON" -> "weapon"; case "DIGGER_LOOT" -> "mining_loot"; case "FISHING_ROD" -> "fishing"; case "TRIDENT" -> "trident"; case "BREAKABLE" -> "durability"; case "BOW" -> "bow"; case "WEARABLE" -> "equippable"; case "CROSSBOW" -> "crossbow"; case "VANISHABLE" -> "vanishing"; case "MACE" -> "mace"; default -> "mining"; })); } return enchantment; } @Override public int getVersionConvertingTo() { return 69; } }
0
0.953133
1
0.953133
game-dev
MEDIA
0.881975
game-dev
0.951419
1
0.951419
Softsplit/sandbox-classic
1,246
Code/Player/PlayerStats.cs
/// <summary> /// Record stats for the local player /// </summary> public sealed class PlayerStats : Component, IPlayerEvent { [RequireComponent] public Player Player { get; set; } float metersTravelled; Vector3 lastPosition; protected override void OnFixedUpdate() { if ( IsProxy ) return; var delta = WorldPosition - lastPosition; lastPosition = WorldPosition; if ( !Player.Controller.IsOnGround ) { return; } var groundDelta = delta.WithZ( 0 ).Length.InchToMeter(); if ( groundDelta > 10 ) groundDelta = 0; metersTravelled += groundDelta; if ( metersTravelled > 10 ) { Sandbox.Services.Stats.Increment( "meters_walked", metersTravelled ); metersTravelled = 0; } } void IPlayerEvent.OnJump() { if ( IsProxy ) return; Sandbox.Services.Stats.Increment( "jump", 1 ); } void IPlayerEvent.OnDamage( IPlayerEvent.DamageParams args ) { if ( IsProxy ) return; Sandbox.Services.Stats.Increment( "damage_taken", args.Damage ); } void IPlayerEvent.OnDied( IPlayerEvent.DiedParams args ) { if ( IsProxy ) return; Sandbox.Services.Stats.Increment( "deaths", 1 ); } void IPlayerEvent.OnSuicide() { if ( IsProxy ) return; Sandbox.Services.Stats.Increment( "suicides", 1 ); } }
0
0.884285
1
0.884285
game-dev
MEDIA
0.748904
game-dev
0.955966
1
0.955966
qq576067421/Fishing
6,242
Client/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dAnimatedSprite.cs
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Sprite/tk2dAnimatedSprite (Obsolete)")] public class tk2dAnimatedSprite : tk2dSprite { #region SpriteAnimatorRouting [SerializeField] tk2dSpriteAnimator _animator = null; public tk2dSpriteAnimator Animator { get { CheckAddAnimatorInternal(); return _animator; } } void CheckAddAnimatorInternal() { if (_animator == null) { _animator = gameObject.GetComponent<tk2dSpriteAnimator>(); if (_animator == null) { _animator = gameObject.AddComponent<tk2dSpriteAnimator>(); _animator.Library = anim; _animator.DefaultClipId = clipId; _animator.playAutomatically = playAutomatically; } } } #endregion // Required for serialization [SerializeField] private tk2dSpriteAnimation anim; [SerializeField] private int clipId = 0; public bool playAutomatically = false; public bool createCollider = false; // Required for backwards compatility protected override bool NeedBoxCollider() { return createCollider; } public tk2dSpriteAnimation Library { get { return Animator.Library; } set { Animator.Library = value; } } public int DefaultClipId { get { return Animator.DefaultClipId; } set { Animator.DefaultClipId = value; } } // Wrapped functions public static bool g_paused { get { return tk2dSpriteAnimator.g_Paused; } set { tk2dSpriteAnimator.g_Paused = value; } } public bool Paused { get { return Animator.Paused; } set { Animator.Paused = value; } } /// <summary> /// Animation complete delegate /// </summary> public delegate void AnimationCompleteDelegate(tk2dAnimatedSprite sprite, int clipId); /// <summary> /// Animation complete event. This is called when the animation has completed playing. Will not trigger on looped animations /// </summary> public AnimationCompleteDelegate animationCompleteDelegate; /// <summary> /// Animation event delegate. /// </summary> public delegate void AnimationEventDelegate(tk2dAnimatedSprite sprite, tk2dSpriteAnimationClip clip, tk2dSpriteAnimationFrame frame, int frameNum); /// <summary> /// Animation event. This is called when the frame displayed has <see cref="tk2dSpriteAnimationFrame.triggerEvent"/> set. /// The triggering frame is passed to the delegate, and the eventInfo / Int / Float can be extracted from there. /// </summary> public AnimationEventDelegate animationEventDelegate; void ProxyCompletedHandler(tk2dSpriteAnimator anim, tk2dSpriteAnimationClip clip) { if (animationCompleteDelegate != null) { int clipId = -1; tk2dSpriteAnimationClip[] clips = (anim.Library != null) ? anim.Library.clips : null; if (clips != null) { for (int i = 0; i < clips.Length; ++i) { if (clips[i] == clip) { clipId = i; break; } } } animationCompleteDelegate(this, clipId); } } void ProxyEventTriggeredHandler(tk2dSpriteAnimator anim, tk2dSpriteAnimationClip clip, int frame) { if (animationEventDelegate != null) { animationEventDelegate(this, clip, clip.frames[frame], frame); } } void OnEnable() { Animator.AnimationCompleted = ProxyCompletedHandler; Animator.AnimationEventTriggered = ProxyEventTriggeredHandler; } void OnDisable() { Animator.AnimationCompleted = null; Animator.AnimationEventTriggered = null; } // execution order on tk2dSpriteAnimator should be AFTER tk2dAnimatedSprite void Start() { CheckAddAnimatorInternal(); } /// <summary> /// Adds a tk2dAnimatedSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry. /// </summary> public static tk2dAnimatedSprite AddComponent(GameObject go, tk2dSpriteAnimation anim, int clipId) { var clip = anim.clips[clipId]; tk2dAnimatedSprite animSprite = go.AddComponent<tk2dAnimatedSprite>(); animSprite.SetSprite(clip.frames[0].spriteCollection, clip.frames[0].spriteId); animSprite.anim = anim; return animSprite; } #region Play public void Play() { if (Animator.DefaultClip != null) { Animator.Play(Animator.DefaultClip); } } public void Play(float clipStartTime) { if (Animator.DefaultClip != null) { Animator.PlayFrom(Animator.DefaultClip, clipStartTime); } } public void PlayFromFrame(int frame) { if (Animator.DefaultClip != null) { Animator.PlayFromFrame(Animator.DefaultClip, frame); } } public void Play(string name) { Animator.Play(name); } public void PlayFromFrame(string name, int frame) { Animator.PlayFromFrame(name, frame); } public void Play(string name, float clipStartTime) { Animator.PlayFrom(name, clipStartTime); } public void Play(tk2dSpriteAnimationClip clip, float clipStartTime) { Animator.PlayFrom(clip, clipStartTime); } public void Play(tk2dSpriteAnimationClip clip, float clipStartTime, float overrideFps) { Animator.Play(clip, clipStartTime, overrideFps); } #endregion public tk2dSpriteAnimationClip CurrentClip { get { return Animator.CurrentClip; } } public float ClipTimeSeconds { get { return Animator.ClipTimeSeconds; } } public float ClipFps { get { return Animator.ClipFps; } set { Animator.ClipFps = value; } } public void Stop() { Animator.Stop(); } public void StopAndResetFrame() { Animator.StopAndResetFrame(); } [System.Obsolete] public bool isPlaying() { return Animator.Playing; } public bool IsPlaying(string name) { return Animator.IsPlaying(name); } public bool IsPlaying(tk2dSpriteAnimationClip clip) { return Animator.IsPlaying(clip); } public bool Playing { get { return Animator.Playing; } } public int GetClipIdByName(string name) { return Animator.GetClipIdByName(name); } public tk2dSpriteAnimationClip GetClipByName(string name) { return Animator.GetClipByName(name); } public static float DefaultFps { get { return tk2dSpriteAnimator.DefaultFps; } } public void Pause() { Animator.Pause(); } public void Resume() { Animator.Resume(); } public void SetFrame(int currFrame) { Animator.SetFrame(currFrame); } public void SetFrame(int currFrame, bool triggerEvent) { Animator.SetFrame(currFrame, triggerEvent); } public void UpdateAnimation(float deltaTime) { Animator.UpdateAnimation(deltaTime); } }
0
0.75807
1
0.75807
game-dev
MEDIA
0.920731
game-dev
0.930884
1
0.930884
ProjectIgnis/CardScripts
3,828
official/c73639099.lua
--セラの蟲惑魔 --Traptrix Sera --scripted by Logical Nonsense local s,id=GetID() function s.initial_effect(c) --Link summon method c:EnableReviveLimit() Link.AddProcedure(c,s.matfilter,1,1) --Unaffected by trap effects, continuous effect local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_IMMUNE_EFFECT) e1:SetCondition(s.immcon) e1:SetValue(s.efilter) c:RegisterEffect(e1) --Special summon a "Traptrix" monster from deck, optional trigger effect local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,0)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_CHAINING) e3:SetProperty(EFFECT_FLAG_DELAY) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1,id) e3:SetCondition(s.spcon) e3:SetTarget(s.sptg) e3:SetOperation(s.spop) c:RegisterEffect(e3) --Set 1 "Trap Hole" normal trap card from deck, optional trigger effect local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(id,1)) e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e5:SetCode(EVENT_CHAINING) e5:SetProperty(EFFECT_FLAG_DELAY) e5:SetRange(LOCATION_MZONE) e5:SetCountLimit(1,{id,1}) e5:SetCondition(s.setcon) e5:SetTarget(s.settg) e5:SetOperation(s.setop) c:RegisterEffect(e5) end s.listed_series={SET_TRAPTRIX,SET_TRAP_HOLE,SET_HOLE} --Link material of a non-link "Traptrix" monster function s.matfilter(c,lc,sumtype,tp) return c:IsSetCard(SET_TRAPTRIX,lc,sumtype,tp) and not c:IsType(TYPE_LINK,lc,sumtype,tp) end --If this card was link summoned function s.immcon(e) return e:GetHandler():IsLinkSummoned() end --Unaffected by trap effects function s.efilter(e,te) return te:IsTrapEffect() end --If a normal trap card is activated function s.spcon(e,tp,eg,ep,ev,re,r,rp) return re:GetActiveType()==TYPE_TRAP and re:IsHasType(EFFECT_TYPE_ACTIVATE) end --Check names of monsters function s.namefilter(c,cd) return c:IsCode(cd) and c:IsFaceup() end --Check for "Traptrix" monster function s.spfilter(c,e,tp) return c:IsSetCard(SET_TRAPTRIX) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not Duel.IsExistingMatchingCard(s.namefilter,tp,LOCATION_ONFIELD,0,1,nil,c:GetCode()) end --Activation legality function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end --Performing the effect of special summoning a "Traptrix" monster with different name from controlled monsters function s.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<1 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if #g>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end --If your "Traptrix" monster effect activates, except this card function s.setcon(e,tp,eg,ep,ev,re,r,rp) return rp==tp and re:IsMonsterEffect() and re:GetHandler():IsSetCard(SET_TRAPTRIX) and re:GetHandler()~=e:GetHandler() end --Check for "Trap Hole" normal trap function s.setfilter(c) return (c:IsSetCard(SET_TRAP_HOLE) or c:IsSetCard(SET_HOLE)) and c:IsNormalTrap() and c:IsSSetable() end --Activation legality function s.settg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.setfilter,tp,LOCATION_DECK,0,1,nil) end end --Performing the effect of setting 1 "Trap Hole" normal trap from deck to S/T zones function s.setop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET) local g=Duel.SelectMatchingCard(tp,s.setfilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SSet(tp,g:GetFirst()) end end
0
0.954741
1
0.954741
game-dev
MEDIA
0.951208
game-dev
0.975835
1
0.975835
Gaby-Station/Gaby-Station
16,766
Content.Shared/Verbs/Verb.cs
// SPDX-FileCopyrightText: 2019 Silver <Silvertorch5@gmail.com> // SPDX-FileCopyrightText: 2019 ZelteHonor <gabrieldionbouchard@gmail.com> // SPDX-FileCopyrightText: 2019 moneyl <8206401+Moneyl@users.noreply.github.com> // SPDX-FileCopyrightText: 2020 Pieter-Jan Briers <pieterjan.briers@gmail.com> // SPDX-FileCopyrightText: 2020 Víctor Aguilera Puerto <6766154+Zumorica@users.noreply.github.com> // SPDX-FileCopyrightText: 2021 Acruid <shatter66@gmail.com> // SPDX-FileCopyrightText: 2021 Metal Gear Sloth <metalgearsloth@gmail.com> // SPDX-FileCopyrightText: 2021 Pieter-Jan Briers <pieterjan.briers+git@gmail.com> // SPDX-FileCopyrightText: 2022 Rane <60792108+Elijahrane@users.noreply.github.com> // SPDX-FileCopyrightText: 2022 ShadowCommander <10494922+ShadowCommander@users.noreply.github.com> // SPDX-FileCopyrightText: 2022 mirrorcult <lunarautomaton6@gmail.com> // SPDX-FileCopyrightText: 2022 wrexbe <81056464+wrexbe@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 DrSmugleaf <DrSmugleaf@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 DrSmugleaf <drsmugleaf@gmail.com> // SPDX-FileCopyrightText: 2023 Jezithyr <jezithyr@gmail.com> // SPDX-FileCopyrightText: 2023 Leon Friedrich <60421075+ElectroJr@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 Slava0135 <super.novalskiy_0135@inbox.ru> // SPDX-FileCopyrightText: 2023 Visne <39844191+Visne@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com> // SPDX-FileCopyrightText: 2023 moonheart08 <moonheart08@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // // SPDX-License-Identifier: MIT using Content.Shared.Database; using Content.Shared.Interaction.Events; using Content.Shared.Inventory; using Robust.Shared.Serialization; using Robust.Shared.Utility; namespace Content.Shared.Verbs { /// <summary> /// Verb objects describe actions that a user can take. The actions can be specified via an Action, local /// events, or networked events. Verbs also provide text, icons, and categories for displaying in the /// context-menu. /// </summary> [Serializable, NetSerializable, Virtual] public class Verb : IComparable { public static string DefaultTextStyleClass = "Verb"; /// <summary> /// Determines the priority of this type of verb when displaying in the verb-menu. See <see /// cref="CompareTo"/>. /// </summary> public virtual int TypePriority => 0; /// <summary> /// Style class for drawing in the context menu /// </summary> public string TextStyleClass = DefaultTextStyleClass; /// <summary> /// This is an action that will be run when the verb is "acted" out. /// </summary> /// <remarks> /// This delegate probably just points to some function in the system assembling this verb. This delegate /// will be run regardless of whether <see cref="ExecutionEventArgs"/> is defined. /// </remarks> [NonSerialized] public Action? Act; /// <summary> /// This is a general local event that will be raised when the verb is executed. /// </summary> /// <remarks> /// If not null, this event will be raised regardless of whether <see cref="Act"/> was run. If this event /// exists purely to call a specific system method, then <see cref="Act"/> should probably be used instead (method /// events are a no-go). /// </remarks> [NonSerialized] public object? ExecutionEventArgs; /// <summary> /// Where do direct the local event. If invalid, the event is not raised directed at any entity. /// </summary> [NonSerialized] public EntityUid EventTarget = EntityUid.Invalid; /// <summary> /// Whether a verb is only defined client-side. Note that this has nothing to do with whether the target of /// the verb is client-side /// </summary> /// <remarks> /// If true, the client will not also ask the server to run this verb when executed locally. This just /// prevents unnecessary network events and "404-verb-not-found" log entries. /// </remarks> [NonSerialized] public bool ClientExclusive; /// <summary> /// The text that the user sees on the verb button. /// </summary> public string Text = string.Empty; /// <summary> /// Sprite of the icon that the user sees on the verb button. /// </summary> public SpriteSpecifier? Icon; /// <summary> /// Name of the category this button is under. Used to group verbs in the context menu. /// </summary> public VerbCategory? Category; /// <summary> /// Whether this verb is disabled. /// </summary> /// <remarks> /// Disabled verbs are shown in the context menu with a slightly darker background color, and cannot be /// executed. It is recommended that a <see cref="Message"/> message be provided outlining why this verb is /// disabled. /// </remarks> public bool Disabled; /// <summary> /// Optional informative message. /// </summary> /// <remarks> /// This will be shown as a tooltip when hovering over this verb in the context menu. Additionally, iF a /// <see cref="Disabled"/> verb is executed, this message will also be shown as a pop-up message. Useful for /// disabled verbs to inform users about why they cannot perform a given action. /// </remarks> public string? Message; /// <summary> /// Determines the priority of the verb. This affects both how the verb is displayed in the context menu /// GUI, and which verb is actually executed when left/alt clicking. /// </summary> /// <remarks> /// Bigger is higher priority (appears first, gets executed preferentially). /// </remarks> public int Priority; /// <summary> /// If this is not null, and no icon or icon texture were specified, a sprite view of this entity will be /// used as the icon for this verb. /// </summary> public NetEntity? IconEntity; /// <summary> /// Whether or not to close the context menu after using it to run this verb. /// </summary> /// <remarks> /// Setting this to false may be useful for repeatable actions, like rotating an object or maybe knocking on /// a window. /// </remarks> public bool? CloseMenu; public virtual bool CloseMenuDefault => true; /// <summary> /// How important is this verb, for the purposes of admin logging? /// </summary> /// <remarks> /// If this is just opening a UI or ejecting an id card, this should probably be low. /// </remarks> public LogImpact Impact = LogImpact.Low; /// <summary> /// Whether this verb requires confirmation before being executed. /// </summary> public bool ConfirmationPopup = false; /// <summary> /// If true, this verb will raise <see cref="ContactInteractionEvent"/>s when executed. If not explicitly /// specified, this will just default to raising the event if <see cref="DefaultDoContactInteraction"/> is /// true and the user is in range. /// </summary> public bool? DoContactInteraction; public virtual bool DefaultDoContactInteraction => false; /// <summary> /// Compares two verbs based on their <see cref="Priority"/>, <see cref="Category"/>, <see cref="Text"/>, /// and <see cref="IconTexture"/>. /// </summary> /// <remarks> /// <para> /// This is comparison is used when storing verbs in a SortedSet. The ordering of verbs determines both how /// the verbs are displayed in the context menu, and the order in which alternative action verbs are /// executed when alt-clicking. /// </para> /// <para> /// If two verbs are equal according to this comparison, they cannot both be added to the same sorted set of /// verbs. This is desirable, given that these verbs would also appear identical in the context menu. /// Distinct verbs should always have a unique and descriptive combination of text, icon, and category. /// </para> /// </remarks> public int CompareTo(object? obj) { if (obj is not Verb otherVerb) return -1; // Sort first by type-priority if (TypePriority != otherVerb.TypePriority) return otherVerb.TypePriority - TypePriority; // Then by verb-priority if (Priority != otherVerb.Priority) return otherVerb.Priority - Priority; // Then try use alphabetical verb categories. Uncategorized verbs always appear first. if (Category?.Text != otherVerb.Category?.Text) { return string.Compare(Category?.Text, otherVerb.Category?.Text, StringComparison.CurrentCulture); } // Then try use alphabetical verb text. if (Text != otherVerb.Text) { return string.Compare(Text, otherVerb.Text, StringComparison.CurrentCulture); } if (IconEntity != otherVerb.IconEntity) { if (IconEntity == null) return -1; if (otherVerb.IconEntity == null) return 1; return IconEntity.Value.CompareTo(otherVerb.IconEntity.Value); } // Finally, compare icon texture paths. Note that this matters for verbs that don't have any text (e.g., the rotate-verbs) return string.Compare(Icon?.ToString(), otherVerb.Icon?.ToString(), StringComparison.CurrentCulture); } // I hate this. Please somebody allow generics to be networked. /// <summary> /// Collection of all verb types, /// </summary> /// <remarks> /// Useful when iterating over verb types, though maybe this should be obtained and stored via reflection or /// something (list of all classes that inherit from Verb). Currently used for networking (apparently Type /// is not serializable?), and resolving console commands. /// </remarks> public static List<Type> VerbTypes = new() { typeof(Verb), typeof(VvVerb), typeof(InteractionVerb), typeof(UtilityVerb), typeof(InnateVerb), typeof(AlternativeVerb), typeof(ActivationVerb), typeof(ExamineVerb), typeof(EquipmentVerb) }; } /// <summary> /// View variables verbs. /// </summary> /// <remarks>Currently only used for the verb that opens the view variables panel.</remarks> [Serializable, NetSerializable] public sealed class VvVerb : Verb { public override int TypePriority => int.MaxValue; } /// <summary> /// Primary interaction verbs. This includes both use-in-hand and interacting with external entities. /// </summary> /// <remarks> /// These verbs those that involve using the hands or the currently held item on some entity. These verbs usually /// correspond to interactions that can be triggered by left-clicking or using 'Z', and often depend on the /// currently held item. These verbs are collectively shown first in the context menu. /// </remarks> [Serializable, NetSerializable] public sealed class InteractionVerb : Verb { public new static string DefaultTextStyleClass = "InteractionVerb"; public override int TypePriority => 4; public override bool DefaultDoContactInteraction => true; public InteractionVerb() : base() { TextStyleClass = DefaultTextStyleClass; } } /// <summary> /// These verbs are similar to the normal interaction verbs, except these interactions are facilitated by the /// currently held entity. /// </summary> /// <remarks> /// The only notable difference between these and InteractionVerbs is that they are obtained by raising an event /// directed at the currently held entity. Distinguishing between utility and interaction verbs helps avoid /// confusion if a component enables verbs both when the item is used on something else, or when it is the /// target of an interaction. These verbs are only obtained if the target and the held entity are NOT the same. /// </remarks> [Serializable, NetSerializable] public sealed class UtilityVerb : Verb { public override int TypePriority => 3; public override bool DefaultDoContactInteraction => true; public UtilityVerb() : base() { TextStyleClass = InteractionVerb.DefaultTextStyleClass; } } /// <summary> /// This is for verbs facilitated by components on the user or their clothing. /// Verbs from clothing, species, etc. rather than a held item. /// </summary> /// <remarks> /// This will get relayed to all clothing (Not pockets) through an inventory relay event. /// </remarks> [Serializable, NetSerializable] public sealed class InnateVerb : Verb { public override int TypePriority => 3; public InnateVerb() : base() { TextStyleClass = InteractionVerb.DefaultTextStyleClass; } } /// <summary> /// Verbs for alternative-interactions. /// </summary> /// <remarks> /// When interacting with an entity via alt + left-click/E/Z the highest priority alt-interact verb is executed. /// These verbs are collectively shown second-to-last in the context menu. /// </remarks> [Serializable, NetSerializable] public sealed class AlternativeVerb : Verb { public override int TypePriority => 2; public new static string DefaultTextStyleClass = "AlternativeVerb"; public override bool DefaultDoContactInteraction => true; public AlternativeVerb() : base() { TextStyleClass = DefaultTextStyleClass; } } /// <summary> /// Activation-type verbs. /// </summary> /// <remarks> /// These are verbs that activate an item in the world but are independent of the currently held items. For /// example, opening a door or a GUI. These verbs should correspond to interactions that can be triggered by /// using 'E', though many of those can also be triggered by left-mouse or 'Z' if there is no other interaction. /// These verbs are collectively shown second in the context menu. /// </remarks> [Serializable, NetSerializable] public sealed class ActivationVerb : Verb { public override int TypePriority => 1; public new static string DefaultTextStyleClass = "ActivationVerb"; public override bool DefaultDoContactInteraction => true; public ActivationVerb() : base() { TextStyleClass = DefaultTextStyleClass; } } [Serializable, NetSerializable] public sealed class ExamineVerb : Verb { public override int TypePriority => 0; public override bool CloseMenuDefault => false; // for examine verbs, this will close the examine tooltip. public bool ShowOnExamineTooltip = true; public bool HoverVerb = false; // aligned to the left, gives text on hover } /// <summary> /// Verbs specifically for interactions that occur with equipped entities. These verbs are unique in that they /// can be used via the stripping UI. Additionally, when getting verbs on an entity with an inventory it will /// these automatically relay the <see cref="GetVerbsEvent{EquipmentVerb}"/> event to all equipped items via a /// <see cref="InventoryRelayedEvent{T}"/>. /// </summary> [Serializable, NetSerializable] public sealed class EquipmentVerb : Verb { public override int TypePriority => 5; } }
0
0.883412
1
0.883412
game-dev
MEDIA
0.670009
game-dev
0.738432
1
0.738432
ClarkGuan/scrcpy-go
1,435
scrcpy/continuous_fire.go
package scrcpy import ( "sync/atomic" "time" ) type continuousFire struct { animator stopFlag int32 Point state int id *int interval time.Duration } func (cf *continuousFire) Start(c Controller, interval time.Duration) { cf.animator.InProgress = cf.inProgress cf.SetInterval(interval) cf.animator.Start(c) } func (cf *continuousFire) SetInterval(interval time.Duration) { if interval < 10*time.Millisecond { cf.interval = 10 * time.Millisecond } else { cf.interval = interval } } func (cf *continuousFire) inProgress(data interface{}) time.Duration { c := data.(Controller) if atomic.LoadInt32(&cf.stopFlag) != 1 { cf.state = cf.state % 2 switch cf.state { case 0: cf.id = fingers.GetId() cf.sendMouseEvent(c, AMOTION_EVENT_ACTION_DOWN, *cf.id) cf.state++ return cf.interval case 1: cf.sendMouseEvent(c, AMOTION_EVENT_ACTION_UP, *cf.id) fingers.Recycle(cf.id) cf.id = nil cf.state++ return cf.interval } panic("can't reach here") } else { if cf.id != nil { cf.sendMouseEvent(c, AMOTION_EVENT_ACTION_UP, *cf.id) fingers.Recycle(cf.id) cf.id = nil } return 0 } } func (cf *continuousFire) Stop() { atomic.StoreInt32(&cf.stopFlag, 1) } func (cf *continuousFire) sendMouseEvent(c Controller, action androidMotionEventAction, id int) error { sme := singleMouseEvent{action: action} sme.id = id sme.Point = cf.Point return c.PushEvent(&sme) }
0
0.65094
1
0.65094
game-dev
MEDIA
0.649991
game-dev
0.838581
1
0.838581
proletariatgames/unreal.hx
1,156
Haxe/Externs/UE4.21/unreal/blueprintgraph/UK2Node_GetInputAxisKeyValue.hx
/** * * WARNING! This file was autogenerated by: * _ _ _ _ __ __ * | | | | | | |\ \ / / * | | | | |_| | \ V / * | | | | _ | / \ * | |_| | | | |/ /^\ \ * \___/\_| |_/\/ \/ * * This file was autogenerated by UnrealHxGenerator using UHT definitions. * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal.blueprintgraph; /** WARNING: This type was defined as MinimalAPI on its declaration. Because of that, its properties/methods are inaccessible **/ @:umodule("BlueprintGraph") @:glueCppIncludes("K2Node_GetInputAxisKeyValue.h") @:uextern @:uclass extern class UK2Node_GetInputAxisKeyValue extends unreal.blueprintgraph.UK2Node_CallFunction { /** Should the binding gather input even when the game is paused **/ @:uproperty public var bExecuteWhenPaused : Bool; /** Prevents actors with lower priority from handling this input **/ @:uproperty public var bConsumeInput : Bool; @:uproperty public var InputAxisKey : unreal.inputcore.FKey; }
0
0.759894
1
0.759894
game-dev
MEDIA
0.730457
game-dev
0.609223
1
0.609223
dengzibiao/moba
2,456
Assets/Editor/Camera_image/Standard Assets/Editor/ImageEffects/EdgeDetectionEditor.cs
using System; using UnityEditor; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [CustomEditor (typeof(EdgeDetection))] class EdgeDetectionEditor : Editor { SerializedObject serObj; SerializedProperty mode; SerializedProperty sensitivityDepth; SerializedProperty sensitivityNormals; SerializedProperty lumThreshold; SerializedProperty edgesOnly; SerializedProperty edgesOnlyBgColor; SerializedProperty edgeExp; SerializedProperty sampleDist; void OnEnable () { serObj = new SerializedObject (target); mode = serObj.FindProperty("mode"); sensitivityDepth = serObj.FindProperty("sensitivityDepth"); sensitivityNormals = serObj.FindProperty("sensitivityNormals"); lumThreshold = serObj.FindProperty("lumThreshold"); edgesOnly = serObj.FindProperty("edgesOnly"); edgesOnlyBgColor = serObj.FindProperty("edgesOnlyBgColor"); edgeExp = serObj.FindProperty("edgeExp"); sampleDist = serObj.FindProperty("sampleDist"); } public override void OnInspectorGUI () { serObj.Update (); GUILayout.Label("Detects spatial differences and converts into black outlines", EditorStyles.miniBoldLabel); EditorGUILayout.PropertyField (mode, new GUIContent("Mode")); if (mode.intValue < 2) { EditorGUILayout.PropertyField (sensitivityDepth, new GUIContent(" Depth Sensitivity")); EditorGUILayout.PropertyField (sensitivityNormals, new GUIContent(" Normals Sensitivity")); } else if (mode.intValue < 4) { EditorGUILayout.PropertyField (edgeExp, new GUIContent(" Edge Exponent")); } else { // lum based mode EditorGUILayout.PropertyField (lumThreshold, new GUIContent(" Luminance Threshold")); } EditorGUILayout.PropertyField (sampleDist, new GUIContent(" Sample Distance")); EditorGUILayout.Separator (); GUILayout.Label ("Background Options"); edgesOnly.floatValue = EditorGUILayout.Slider (" Edges only", edgesOnly.floatValue, 0.0f, 1.0f); EditorGUILayout.PropertyField (edgesOnlyBgColor, new GUIContent (" Color")); serObj.ApplyModifiedProperties(); } } }
0
0.911229
1
0.911229
game-dev
MEDIA
0.800107
game-dev
0.689436
1
0.689436
shxp3/CrossSine
2,577
src/main/java/net/ccbluex/liquidbounce/features/module/modules/other/hackercheck/checks/combat/ReachCheck.java
package net.ccbluex.liquidbounce.features.module.modules.other.hackercheck.checks.combat; import net.ccbluex.liquidbounce.features.module.modules.other.HackerDetector; import net.ccbluex.liquidbounce.features.module.modules.other.hackercheck.Check; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; public class ReachCheck extends Check { int swingBuffer; public ReachCheck(EntityOtherPlayerMP playerMP) { super(playerMP); name = "Reach"; checkViolationLevel = 5; } public void onLivingUpdate() { if (HackerDetector.INSTANCE.reachValue.get()) { EntityPlayer target = null; for (Entity entity : mc.theWorld.loadedEntityList) { if (entity instanceof EntityPlayer) { float yaw = getRotationsForEntity(this.handlePlayer, (EntityPlayer) entity)[0]; if (this.handlePlayer.rotationYaw >= yaw - 20.0F && this.handlePlayer.rotationYaw <= yaw + 20.0F) { target = (EntityPlayer) entity; } } } if (target != null) { if (this.handlePlayer.isSwingInProgress) { this.swingBuffer++; } if (this.swingBuffer >= 10 && target.hurtResistantTime > 8 && this.handlePlayer.getDistanceSqToEntity(target) >= 3.5D) { flag("Attack other entity for long distance", 1.0D); } } } } public static float[] getRotationsForEntity(EntityPlayer player, EntityPlayer target) { if (player != null && target != null) { double diffX = target.posX - player.posX; double diffY = target.posY + target.getEyeHeight() * 0.9D - (player.posY + player.getEyeHeight()); double diffZ = target.posZ - player.posZ; double dist = Math.sqrt(diffX * diffX + diffZ * diffZ); float yaw = (float) (Math.atan2(diffZ, diffX) * 180.0D / Math.PI - 90.0D); float pitch = (float) -(Math.atan2(diffY, dist) * 180.0D / Math.PI) + 11.0F; return new float[] { player.rotationYaw + MathHelper.wrapAngleTo180_float(yaw - player.rotationYaw), player.rotationPitch + MathHelper.wrapAngleTo180_float(pitch - player.rotationPitch) }; } return new float[] { player.rotationYaw, player.rotationPitch }; } }
0
0.810495
1
0.810495
game-dev
MEDIA
0.738626
game-dev
0.941942
1
0.941942
lewislepton/kha-tutorial-series
2,175
117_canvasRefineLibrary/Libraries/lkl/Sources/lkl/collide/Rectangle.hx
package lkl.collide; import kha.math.Vector2; import lkl.Object; import lkl.tool.Direction; class Rectangle extends Object { public var onGround = false; var collision:Int; public function new(x:Float, y:Float, width:Float, height:Float){ super(x, y, width, height); } public function overlap(other:Rectangle){ return position.x <= other.position.x + other.width && position.x + width >= other.position.x && position.y <= other.position.y + other.height && position.y + height >= other.position.y; } public function collideRect(entity:Entity):Bool { checkRectCollision(); var dx = (this.position.x + this.width / 2) - (entity.position.x + entity.width / 2); var dy = (this.position.y + this.height / 2) - (entity.position.y + entity.height / 2); var combined:Vector2 = new Vector2(); combined.x = this.center.x + entity.center.x; combined.y = this.center.y + entity.center.y; if (Math.abs(dx) < combined.x){ if (Math.abs(dy) < combined.y){ var overlap:Vector2 = new Vector2(); overlap.x = combined.x - Math.abs(dx); overlap.y = combined.y - Math.abs(dy); if (overlap.x >= overlap.y){ if (dy > 0){ this.collision = Direction.UP; this.position.y += overlap.y; } else { this.collision = Direction.DOWN; this.position.y -= overlap.y; } } else { if (dx > 0){ this.collision = Direction.LEFT; this.position.x += overlap.x; } else { this.collision = Direction.RIGHT; this.position.x -= overlap.x; } } } else { this.collision = Direction.NONE; } } else { this.collision = Direction.NONE; } return false; } function checkRectCollision(){ if (collision == Direction.DOWN && velocity.y >= 0){ onGround = true; velocity.y = 0; } else if (collision == Direction.UP && velocity.y <= 0){ onGround = false; velocity.y = 0; } else if (collision == Direction.RIGHT && velocity.x >= 0){ onGround = false; velocity.x = 0; } else if (collision == Direction.LEFT && velocity.x <= 0){ onGround = false; velocity.x = 0; } if (collision != Direction.DOWN && velocity.y > 0){ onGround = false; } } }
0
0.844271
1
0.844271
game-dev
MEDIA
0.857761
game-dev,web-frontend
0.962054
1
0.962054
AscEmu/AscEmu
12,268
src/collision/Management/MMapManager.cpp
/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2025 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by //-V1042 * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MMapManager.h" #include "MapDefines.h" #include "Debugging/Errors.h" #include "Logging/Logger.hpp" #include "Server/World.h" namespace MMAP { // ######################## MMapManager ######################## MMapManager::~MMapManager() { loadedMMaps.clear(); // by now we should not have maps loaded // if we had, tiles in MMapData->mmapLoadedTiles, their actual data is lost! } void MMapManager::InitializeThreadUnsafe(const std::vector<uint32_t>& mapIds) { // the caller must pass the list of all mapIds that will be used in the VMapManager2 lifetime for (const uint32_t& mapId : mapIds) loadedMMaps.insert(MMapDataSet::value_type(mapId, nullptr)); thread_safe_environment = false; } MMapDataSet::const_iterator MMapManager::GetMMapData(uint32_t mapId) const { // return the iterator if found or end() if not found/NULL MMapDataSet::const_iterator itr = loadedMMaps.find(mapId); if (itr != loadedMMaps.cend() && !itr->second) itr = loadedMMaps.cend(); return itr; } bool MMapManager::loadMapData(uint32_t mapId) { // we already have this map loaded? MMapDataSet::iterator itr = loadedMMaps.find(mapId); if (itr != loadedMMaps.end()) { if (itr->second) return true; } else { if (thread_safe_environment) itr = loadedMMaps.insert(MMapDataSet::value_type(mapId, nullptr)).first; else { sLogger.failure("Invalid mapId {} passed to MMapManager after startup in thread unsafe environment", mapId); ASSERT(false); } } // load and init dtNavMesh - read parameters from file std::string dataDir = worldConfig.server.dataDir + "mmaps/"; uint32_t pathLen = static_cast<uint32_t>(dataDir.length() + strlen("%04i.mmap") + 1); auto fileName = std::make_unique<char[]>(pathLen); snprintf(fileName.get(), pathLen, (dataDir + "%04i.mmap").c_str(), mapId); FILE* file = fopen(fileName.get(), "rb"); if (!file) { sLogger.debug("MMAP:loadMapData: Error: Could not open mmap file '{}'", fileName.get()); return false; } dtNavMeshParams params; int count = static_cast<int>(fread(&params, sizeof(dtNavMeshParams), 1, file)); fclose(file); if (count != 1) { sLogger.failure("Error: Could not read params from file '{}'", fileName.get()); return false; } dtNavMesh* mesh = dtAllocNavMesh(); ASSERT(mesh); if (dtStatusFailed(mesh->init(&params))) { dtFreeNavMesh(mesh); sLogger.failure("Failed to initialize dtNavMesh for mmap {:04} from file {}", mapId, fileName.get()); return false; } sLogger.debug("MMAP:loadMapData: Loaded {:04}.mmap", mapId); // store inside our map list itr->second = std::make_unique<MMapData>(mesh); itr->second->mmapLoadedTiles.clear(); return true; } uint32_t MMapManager::packTileID(int32_t x, int32_t y) { return uint32_t(x << 16 | y); } bool MMapManager::loadMap(const std::string& basePath, uint32_t mapId, int32_t x, int32_t y) { // make sure the mmap is loaded and ready to load tiles if (!loadMapData(mapId)) return false; // get this mmap data MMapData* mmap = loadedMMaps[mapId].get(); ASSERT(mmap->navMesh); // check if we already have this tile loaded uint32_t packedGridPos = packTileID(x, y); if (mmap->mmapLoadedTiles.find(packedGridPos) != mmap->mmapLoadedTiles.end()) return false; // load this tile :: /MMMXXYY.mmtile uint32_t pathLen = static_cast<uint32_t>(basePath.length() + strlen("/%04i%02i%02i.mmtile") + 1); auto fileName = std::make_unique<char[]>(pathLen); snprintf(fileName.get(), pathLen, (basePath + "/%04i%02i%02i.mmtile").c_str(), mapId, x, y); FILE* file = fopen(fileName.get(), "rb"); if (!file) { sLogger.debug("Could not open mmtile file '{}'", fileName.get()); return false; } // read header MmapTileHeader fileHeader; if (fread(&fileHeader, sizeof(MmapTileHeader), 1, file) != 1 || fileHeader.mmapMagic != MMAP_MAGIC) { sLogger.failure("Bad header in mmap {:04}{:02}{:02}.mmtile", mapId, x, y); fclose(file); return false; } if (fileHeader.mmapVersion != MMAP_VERSION) { sLogger.failure("{:04}{:02}{:02}.mmtile was built with generator v{}, expected v{}", mapId, x, y, fileHeader.mmapVersion, MMAP_VERSION); fclose(file); return false; } unsigned char* data = (unsigned char*)dtAlloc(fileHeader.size, DT_ALLOC_PERM); ASSERT(data); size_t result = fread(data, fileHeader.size, 1, file); if (!result) { sLogger.failure("Bad header or data in mmap {:04}{:02}{:02}.mmtile", mapId, x, y); fclose(file); return false; } fclose(file); dtMeshHeader* header = (dtMeshHeader*)data; dtTileRef tileRef = 0; // memory allocated for data is now managed by detour, and will be deallocated when the tile is removed if (dtStatusSucceed(mmap->navMesh->addTile(data, fileHeader.size, DT_TILE_FREE_DATA, 0, &tileRef))) { mmap->mmapLoadedTiles.insert(std::pair<uint32_t, dtTileRef>(packedGridPos, tileRef)); ++loadedTiles; sLogger.debug("MMAP:loadMap: Loaded mmtile {:04}[{:02}, {:02}] into {:04}[{:02}, {:02}]", mapId, x, y, mapId, header->x, header->y); return true; } else { sLogger.debug("MMAP:loadMap: Could not load {:04}{:02}{:02}.mmtile into navmesh", mapId, x, y); dtFree(data); return false; } } bool MMapManager::unloadMap(uint32_t mapId, int32_t x, int32_t y) { // check if we have this map loaded MMapDataSet::const_iterator itr = GetMMapData(mapId); if (itr == loadedMMaps.end()) { // file may not exist, therefore not loaded sLogger.debug("MMAP:unloadMap: Asked to unload not loaded navmesh map. {:04}{:02}{:02}.mmtile", mapId, x, y); return false; } MMapData* mmap = itr->second.get(); // check if we have this tile loaded uint32_t packedGridPos = packTileID(x, y); if (mmap->mmapLoadedTiles.find(packedGridPos) == mmap->mmapLoadedTiles.end()) { // file may not exist, therefore not loaded sLogger.debug("MMAP:unloadMap: Asked to unload not loaded navmesh tile. {:04}{:02}{:02}.mmtile", mapId, x, y); return false; } dtTileRef tileRef = mmap->mmapLoadedTiles[packedGridPos]; // unload, and mark as non loaded if (dtStatusFailed(mmap->navMesh->removeTile(tileRef, nullptr, nullptr))) { // this is technically a memory leak // if the grid is later reloaded, dtNavMesh::addTile will return error but no extra memory is used // we cannot recover from this error - assert out sLogger.failure("Could not unload {:04}{:02}{:02}.mmtile from navmesh", mapId, x, y); } else { mmap->mmapLoadedTiles.erase(packedGridPos); --loadedTiles; sLogger.debug("MMAP:unloadMap: Unloaded mmtile {:04}[{:02}, {:02}] from {:04}", mapId, x, y, mapId); return true; } return false; } bool MMapManager::unloadMap(uint32_t mapId) { MMapDataSet::iterator itr = loadedMMaps.find(mapId); if (itr == loadedMMaps.end() || !itr->second) { // file may not exist, therefore not loaded sLogger.debug("MMAP:unloadMap: Asked to unload not loaded navmesh map. {:04}.mmtile", mapId); return false; } // unload all tiles from given map MMapData* mmap = itr->second.get(); for (MMapTileSet::iterator i = mmap->mmapLoadedTiles.begin(); i != mmap->mmapLoadedTiles.end(); ++i) { uint32_t x = (i->first >> 16); uint32_t y = (i->first & 0x0000FFFF); if (dtStatusFailed(mmap->navMesh->removeTile(i->second, nullptr, nullptr))) sLogger.failure("Could not unload {:04}{:02}{:02}.mmtile from navmesh", mapId, x, y); else { --loadedTiles; sLogger.debug("MMAP:unloadMap: Unloaded mmtile {:04}[{:02}, {:02}] from {:04}", mapId, x, y, mapId); } } itr->second = nullptr; sLogger.debug("MMAP:unloadMap: Unloaded {:04}.mmap", mapId); return true; } bool MMapManager::unloadMapInstance(uint32_t mapId, uint32_t instanceId) { // check if we have this map loaded MMapDataSet::const_iterator itr = GetMMapData(mapId); if (itr == loadedMMaps.end()) { // file may not exist, therefore not loaded sLogger.debug("MMAP:unloadMapInstance: Asked to unload not loaded navmesh map {:04}", mapId); return false; } MMapData* mmap = itr->second.get(); if (mmap->navMeshQueries.find(instanceId) == mmap->navMeshQueries.end()) { sLogger.debug("MMAP:unloadMapInstance: Asked to unload not loaded dtNavMeshQuery mapId {:04} instanceId {}", mapId, instanceId); return false; } dtNavMeshQuery* query = mmap->navMeshQueries[instanceId]; dtFreeNavMeshQuery(query); mmap->navMeshQueries.erase(instanceId); sLogger.debug("MMAP:unloadMapInstance: Unloaded mapId {:04} instanceId {}", mapId, instanceId); return true; } dtNavMesh const* MMapManager::GetNavMesh(uint32_t mapId) { MMapDataSet::const_iterator itr = GetMMapData(mapId); if (itr == loadedMMaps.end()) return nullptr; return itr->second->navMesh; } dtNavMeshQuery const* MMapManager::GetNavMeshQuery(uint32_t mapId, uint32_t instanceId) { MMapDataSet::const_iterator itr = GetMMapData(mapId); if (itr == loadedMMaps.end()) return nullptr; MMapData* mmap = itr->second.get(); if (mmap->navMeshQueries.find(instanceId) == mmap->navMeshQueries.end()) { // allocate mesh query dtNavMeshQuery* query = dtAllocNavMeshQuery(); ASSERT(query); if (dtStatusFailed(query->init(mmap->navMesh, 1024))) { dtFreeNavMeshQuery(query); sLogger.failure("Failed to initialize dtNavMeshQuery for mapId {:04} instanceId {}", mapId, instanceId); return nullptr; } sLogger.debug("MMAP:GetNavMeshQuery: created dtNavMeshQuery for mapId {:04} instanceId {}", mapId, instanceId); mmap->navMeshQueries.insert(std::pair<uint32_t, dtNavMeshQuery*>(instanceId, query)); } return mmap->navMeshQueries[instanceId]; } }
0
0.955511
1
0.955511
game-dev
MEDIA
0.693419
game-dev
0.976445
1
0.976445
Kaedrin/nwn2cc
2,418
NWN2 WIP/Source/ScriptMaster_146/cmi_s0_shldward.NSS
//:://///////////////////////////////////////////// //:: Shield of Warding //:: cmi_s0_shldward //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: July 5, 2007 //::////////////////////////////////////////////// // Known issues: This should stack with vs Align, vs Damage, vs Racial, and vs Specific_Align as well. // Will need to redo the GetAC to account for it, wrapping it as a new function in the cmi_ginc_spells. // "StackShieldBonus(object oShield, int nBonus)" that checks all Item_Props listed above. //x2_inc_itemprop for item properties, reference marker. #include "cmi_ginc_spells" #include "x2_inc_spellhook" #include "x0_i0_spells" void main() { if (!X2PreSpellCastCode()) { // If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell return; } int nSpellID = SPELL_Shield_Warding; int nCasterLvl = GetPalRngCasterLevel(); float fDuration = TurnsToSeconds( nCasterLvl ); fDuration = ApplyMetamagicDurationMods(fDuration); effect eVis = EffectVisualEffect( VFX_DUR_SPELL_BLESS_WEAPON ); eVis = SetEffectSpellId(eVis, nSpellID); eVis = SupernaturalEffect(eVis); object oShield = IPGetTargetedOrEquippedShield(); object oHolder = GetItemPossessor(oShield); if (GetHasSpellEffect(nSpellID, oHolder)) { SendMessageToPC(OBJECT_SELF, "Shield of Warding is already active on the target. Wait for the spell to expire."); } int nEnhanceBonus = 1 + (nCasterLvl/5); if (nEnhanceBonus > 5) nEnhanceBonus = 5; int nReflex = nEnhanceBonus; if(GetIsObjectValid(oShield) ) { SignalEvent(oShield, EventSpellCastAt(OBJECT_SELF, GetSpellId(), FALSE)); int nCurrent = IPGetWeaponEnhancementBonus(oShield,ITEM_PROPERTY_AC_BONUS); if (GetLastSpellCastClass() == 6) nEnhanceBonus = nEnhanceBonus + nCurrent; else nEnhanceBonus = nCurrent++; IPSafeAddItemProperty(oShield, ItemPropertyACBonus(nEnhanceBonus), fDuration,X2_IP_ADDPROP_POLICY_REPLACE_EXISTING); IPSafeAddItemProperty(oShield, ItemPropertyBonusSavingThrow(IP_CONST_SAVEBASETYPE_REFLEX, nReflex), fDuration,X2_IP_ADDPROP_POLICY_REPLACE_EXISTING); ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eVis, oHolder , fDuration); return; } else { FloatingTextStringOnCreature("*Spell Failed: Target must be a shield or creature with a shield equipped.*", OBJECT_SELF); return; } }
0
0.920773
1
0.920773
game-dev
MEDIA
0.871134
game-dev
0.938816
1
0.938816
BennyQBD/3DGameProgrammingTutorial
1,461
src/platform/sdl/sdlApplication.cpp
#include "sdlApplication.hpp" #include "core/common.hpp" #include <SDL2/SDL.h> uint32 SDLApplication::numInstances = 0; SDLApplication* SDLApplication::create() { const uint32 flags = SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_EVENTS; uint32 initialized = SDL_WasInit(flags); if(initialized != flags && SDL_Init(flags) != 0) { DEBUG_LOG("SDLApplication", LOG_ERROR, "SDL_Init: %s", SDL_GetError()); return nullptr; } return new SDLApplication(); } SDLApplication::SDLApplication() { numInstances++; isAppRunning = true; } SDLApplication::~SDLApplication() { numInstances--; if(numInstances == 0) { SDL_Quit(); } } void SDLApplication::processMessages(double delta, IApplicationEventHandler& eventHandler) { SDL_Event e; (void)delta; while(SDL_PollEvent(&e)) { switch(e.type){ case SDL_KEYDOWN: eventHandler.onKeyDown(e.key.keysym.scancode, e.key.repeat != 0); break; case SDL_KEYUP: eventHandler.onKeyUp(e.key.keysym.scancode, e.key.repeat != 0); break; case SDL_MOUSEBUTTONDOWN: eventHandler.onMouseDown(e.button.button, e.button.clicks); break; case SDL_MOUSEBUTTONUP: eventHandler.onMouseUp(e.button.button, e.button.clicks); break; case SDL_MOUSEMOTION: eventHandler.onMouseMove(e.motion.x, e.motion.y, e.motion.xrel, e.motion.yrel); break; case SDL_QUIT: isAppRunning = false; break; default: break; }; } } bool SDLApplication::isRunning() { return isAppRunning; }
0
0.868249
1
0.868249
game-dev
MEDIA
0.815158
game-dev
0.879415
1
0.879415
StranikS-Scan/WorldOfTanks-Decompiled
6,477
source/res/scripts/common/battle_results_shared.py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/common/battle_results_shared.py import struct from itertools import izip from constants import PREMIUM_TYPE, PREM_BONUS_TYPES VEH_INTERACTION_DETAILS = (('spotted', 'B', 1, 0), ('deathReason', 'b', 10, -1), ('directHits', 'H', 65535, 0), ('directEnemyHits', 'H', 65535, 0), ('explosionHits', 'H', 65535, 0), ('piercings', 'H', 65535, 0), ('piercingEnemyHits', 'H', 65535, 0), ('damageDealt', 'I', 4294967295L, 0), ('damageAssistedTrack', 'H', 65535, 0), ('damageAssistedRadio', 'H', 65535, 0), ('damageAssistedStun', 'H', 65535, 0), ('damageAssistedSmoke', 'H', 65535, 0), ('damageAssistedInspire', 'H', 65535, 0), ('crits', 'I', 4294967295L, 0), ('fire', 'H', 65535, 0), ('stunNum', 'H', 65535, 0), ('stunDuration', 'f', 65535.0, 0.0), ('damageBlockedByArmor', 'I', 4294967295L, 0), ('damageReceived', 'H', 65535, 0), ('rickochetsReceived', 'H', 65535, 0), ('noDamageDirectHitsReceived', 'H', 65535, 0), ('targetKills', 'B', 255, 0)) VEH_INTERACTION_DETAILS_NAMES = [ x[0] for x in VEH_INTERACTION_DETAILS ] VEH_INTERACTION_DETAILS_MAX_VALUES = dict(((x[0], x[2]) for x in VEH_INTERACTION_DETAILS)) VEH_INTERACTION_DETAILS_INIT_VALUES = [ x[3] for x in VEH_INTERACTION_DETAILS ] VEH_INTERACTION_DETAILS_LAYOUT = ''.join([ x[1] for x in VEH_INTERACTION_DETAILS ]) VEH_INTERACTION_DETAILS_INDICES = dict(((x[1][0], x[0]) for x in enumerate(VEH_INTERACTION_DETAILS))) VEH_INTERACTION_DETAILS_TYPES = dict(((x[0], x[1]) for x in VEH_INTERACTION_DETAILS)) VEH_INTERACTIVE_STATS = ('xp', 'damageDealt', 'capturePts', 'flagActions', 'winPoints', 'deathCount', 'resourceAbsorbed', 'stopRespawn', 'equipmentDamage', 'equipmentKills') VEH_INTERACTIVE_STATS_INDICES = dict(((x[1], x[0]) for x in enumerate(VEH_INTERACTIVE_STATS))) AVATAR_PRIVATE_STATS = ('ragePoints',) AVATAR_PRIVATE_STATS_INDICES = dict(((x[1], x[0]) for x in enumerate(AVATAR_PRIVATE_STATS))) _PREM_TYPE_TO_FACTOR100_NAMES = {PREM_BONUS_TYPES.CREDITS: {PREMIUM_TYPE.BASIC: 'premiumCreditsFactor100', PREMIUM_TYPE.PLUS: 'premiumPlusCreditsFactor100', PREMIUM_TYPE.VIP: 'premiumVipCreditsFactor100'}, PREM_BONUS_TYPES.XP: {PREMIUM_TYPE.BASIC: 'premiumXPFactor100', PREMIUM_TYPE.PLUS: 'premiumPlusXPFactor100', PREMIUM_TYPE.VIP: 'premiumVipXPFactor100'}, PREM_BONUS_TYPES.TMEN_XP: {PREMIUM_TYPE.BASIC: 'premiumTmenXPFactor100', PREMIUM_TYPE.PLUS: 'premiumPlusTmenXPFactor100', PREMIUM_TYPE.VIP: 'premiumVipXPTmenFactor100'}, PREM_BONUS_TYPES.DYN_CURRENCIES: {PREMIUM_TYPE.BASIC: 'premiumFactor100', PREMIUM_TYPE.PLUS: 'premiumPlusFactor100', PREMIUM_TYPE.VIP: 'premiumVipFactor100'}} class UNIT_CLAN_MEMBERSHIP: NONE = 0 ANY = 1 SAME = 2 def dictToList(indices, d): l = [None] * len(indices) for name, index in indices.iteritems(): l[index] = d[name] return l def listToDict(names, l): d = {} for x in enumerate(names): d[x[1]] = l[x[0]] return d class _VehicleInteractionDetailsItem(object): @staticmethod def __fmt2py(format): return float if format in ('f',) else int def __init__(self, values, offset): self.__values = values self.__offset = offset def __getitem__(self, key): return self.__values[self.__offset + VEH_INTERACTION_DETAILS_INDICES[key]] def __setitem__(self, key, value): self.__values[self.__offset + VEH_INTERACTION_DETAILS_INDICES[key]] = min(self.__fmt2py(VEH_INTERACTION_DETAILS_TYPES[key])(value), VEH_INTERACTION_DETAILS_MAX_VALUES[key]) def __str__(self): return str(dict(self)) def __iter__(self): return izip(VEH_INTERACTION_DETAILS_NAMES, self.__values[self.__offset:]) class VehicleInteractionDetails(object): def __init__(self, uniqueVehIDs, values): self.__uniqueVehIDs = uniqueVehIDs self.__values = values size = len(VEH_INTERACTION_DETAILS) self.__offsets = dict(((x[1], x[0] * size) for x in enumerate(uniqueVehIDs))) @staticmethod def fromPacked(packed): count = len(packed) / struct.calcsize(''.join(['<2I', VEH_INTERACTION_DETAILS_LAYOUT])) packedVehIDsLayout = '<%dI' % (2 * count,) packedVehIDsLen = struct.calcsize(packedVehIDsLayout) flatIDs = struct.unpack(packedVehIDsLayout, packed[:packedVehIDsLen]) uniqueVehIDs = [] for i in xrange(0, len(flatIDs), 2): uniqueVehIDs.append((flatIDs[i], flatIDs[i + 1])) values = struct.unpack('<' + VEH_INTERACTION_DETAILS_LAYOUT * count, packed[packedVehIDsLen:]) return VehicleInteractionDetails(uniqueVehIDs, values) def __getitem__(self, uniqueVehID): if not isinstance(uniqueVehID, tuple): raise UserWarning('Argument uniqueVehID should be tuple: {}'.format(uniqueVehID)) offset = self.__offsets.get(uniqueVehID, None) if offset is None: self.__uniqueVehIDs.append(uniqueVehID) offset = len(self.__values) self.__values += VEH_INTERACTION_DETAILS_INIT_VALUES self.__offsets[uniqueVehID] = offset return _VehicleInteractionDetailsItem(self.__values, offset) def __contains__(self, uniqueVehID): if not isinstance(uniqueVehID, tuple): raise UserWarning('Argument uniqueVehID should be tuple: {}'.format(uniqueVehID)) return uniqueVehID in self.__offsets def __str__(self): return str(self.toDict()) def pack(self): count = len(self.__uniqueVehIDs) flatIDs = [] for uniqueID in self.__uniqueVehIDs: flatIDs.append(uniqueID[0]) flatIDs.append(uniqueID[1]) try: packed = struct.pack(('<%dI' % (2 * count)), *flatIDs) + struct.pack(('<' + VEH_INTERACTION_DETAILS_LAYOUT * count), *self.__values) except Exception as e: from debug_utils import LOG_ERROR LOG_ERROR('PACKING EXCEPTION', e, str(self)) packed = '' return packed def toDict(self): return dict(self.iteritems()) def iteritems(self): for vehInfo, offset in self.__offsets.iteritems(): yield (vehInfo, dict(_VehicleInteractionDetailsItem(self.__values, offset)))
0
0.820198
1
0.820198
game-dev
MEDIA
0.798548
game-dev
0.839505
1
0.839505
boo-lang/boo
2,729
src/Boo.Lang/GenericGeneratorEnumerator.cs
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Boo.Lang { using System; using System.Collections; using System.Collections.Generic; public abstract class GenericGeneratorEnumerator<T> : IEnumerator<T> { protected T _current; // HACK: _state should be protected, not public. // Marked public because of a bug in Mono. See BOO-796 and // http://lists.ximian.com/pipermail/mono-devel-list/2007-February/022431.html public int _state; public GenericGeneratorEnumerator() { _state = 0; } public T Current { get { return _current; } } object IEnumerator.Current { get { return _current; } } public virtual void Dispose() { } public void Reset() { // We cannot reset the local variables of the generator method, // so let's do it like C# and throw a NotSupportedException throw new NotSupportedException(); } public abstract bool MoveNext(); protected bool Yield(int state, T value) { _state = state; _current = value; return true; } protected bool YieldDefault(int state) { _state = state; _current = default(T); return true; } } }
0
0.859377
1
0.859377
game-dev
MEDIA
0.183736
game-dev
0.642473
1
0.642473
disruption01/BiS-Tooltip_335a_backport
58,091
Libs/AceConfig-3.0/AceConfigDialog-3.0/AceConfigDialog-3.0.lua
--- AceConfigDialog-3.0 generates AceGUI-3.0 based windows based on option tables. -- @class file -- @name AceConfigDialog-3.0 -- @release $Id: AceConfigDialog-3.0.lua 1225 2019-08-06 13:37:52Z nevcairiel $ local LibStub = LibStub local gui = LibStub("AceGUI-3.0") local reg = LibStub("AceConfigRegistry-3.0") local MAJOR, MINOR = "AceConfigDialog-3.0", 78 local AceConfigDialog, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceConfigDialog then return end AceConfigDialog.OpenFrames = AceConfigDialog.OpenFrames or {} AceConfigDialog.Status = AceConfigDialog.Status or {} AceConfigDialog.frame = AceConfigDialog.frame or CreateFrame("Frame") AceConfigDialog.frame.apps = AceConfigDialog.frame.apps or {} AceConfigDialog.frame.closing = AceConfigDialog.frame.closing or {} AceConfigDialog.frame.closeAllOverride = AceConfigDialog.frame.closeAllOverride or {} -- Lua APIs local tconcat, tinsert, tsort, tremove = table.concat, table.insert, table.sort, table.remove local strmatch, format = string.match, string.format local assert, loadstring, error = assert, loadstring, error local pairs, next, select, type, unpack, wipe = pairs, next, select, type, unpack, wipe local rawset, tostring, tonumber = rawset, tostring, tonumber local math_min, math_max, math_floor = math.min, math.max, math.floor -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: NORMAL_FONT_COLOR, GameTooltip, StaticPopupDialogs, ACCEPT, CANCEL, StaticPopup_Show -- GLOBALS: PlaySound, GameFontHighlight, GameFontHighlightSmall, GameFontHighlightLarge -- GLOBALS: CloseSpecialWindows, InterfaceOptions_AddCategory, geterrorhandler local emptyTbl = {} --[[ xpcall safecall implementation ]] local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end local function CreateDispatcher(argCount) local code = [[ local xpcall, eh = ... local method, ARGS local function call() return method(ARGS) end local function dispatch(func, ...) method = func if not method then return end ARGS = ... return xpcall(call, eh) end return dispatch ]] local ARGS = {} for i = 1, argCount do ARGS[i] = "arg"..i end code = code:gsub("ARGS", tconcat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) Dispatchers[0] = function(func) return xpcall(func, errorhandler) end local function safecall(func, ...) return Dispatchers[select("#", ...)](func, ...) end local width_multiplier = 170 --[[ Group Types Tree - All Descendant Groups will all become nodes on the tree, direct child options will appear above the tree - Descendant Groups with inline=true and thier children will not become nodes Tab - Direct Child Groups will become tabs, direct child options will appear above the tab control - Grandchild groups will default to inline unless specified otherwise Select- Same as Tab but with entries in a dropdown rather than tabs Inline Groups - Will not become nodes of a select group, they will be effectivly part of thier parent group seperated by a border - If declared on a direct child of a root node of a select group, they will appear above the group container control - When a group is displayed inline, all descendants will also be inline members of the group ]] -- Recycling functions local new, del, copy --newcount, delcount,createdcount,cached = 0,0,0 do local pool = setmetatable({},{__mode="k"}) function new() --newcount = newcount + 1 local t = next(pool) if t then pool[t] = nil return t else --createdcount = createdcount + 1 return {} end end function copy(t) local c = new() for k, v in pairs(t) do c[k] = v end return c end function del(t) --delcount = delcount + 1 wipe(t) pool[t] = true end -- function cached() -- local n = 0 -- for k in pairs(pool) do -- n = n + 1 -- end -- return n -- end end -- picks the first non-nil value and returns it local function pickfirstset(...) for i=1,select("#",...) do if select(i,...)~=nil then return select(i,...) end end end --gets an option from a given group, checking plugins local function GetSubOption(group, key) if group.plugins then for plugin, t in pairs(group.plugins) do if t[key] then return t[key] end end end return group.args[key] end --Option member type definitions, used to decide how to access it --Is the member Inherited from parent options local isInherited = { set = true, get = true, func = true, confirm = true, validate = true, disabled = true, hidden = true } --Does a string type mean a literal value, instead of the default of a method of the handler local stringIsLiteral = { name = true, desc = true, icon = true, usage = true, width = true, image = true, fontSize = true, } --Is Never a function or method local allIsLiteral = { type = true, descStyle = true, imageWidth = true, imageHeight = true, } --gets the value for a member that could be a function --function refs are called with an info arg --every other type is returned local function GetOptionsMemberValue(membername, option, options, path, appName, ...) --get definition for the member local inherits = isInherited[membername] --get the member of the option, traversing the tree if it can be inherited local member if inherits then local group = options if group[membername] ~= nil then member = group[membername] end for i = 1, #path do group = GetSubOption(group, path[i]) if group[membername] ~= nil then member = group[membername] end end else member = option[membername] end --check if we need to call a functon, or if we have a literal value if ( not allIsLiteral[membername] ) and ( type(member) == "function" or ((not stringIsLiteral[membername]) and type(member) == "string") ) then --We have a function to call local info = new() --traverse the options table, picking up the handler and filling the info with the path local handler local group = options handler = group.handler or handler for i = 1, #path do group = GetSubOption(group, path[i]) info[i] = path[i] handler = group.handler or handler end info.options = options info.appName = appName info[0] = appName info.arg = option.arg info.handler = handler info.option = option info.type = option.type info.uiType = "dialog" info.uiName = MAJOR local a, b, c ,d --using 4 returns for the get of a color type, increase if a type needs more if type(member) == "function" then --Call the function a,b,c,d = member(info, ...) else --Call the method if handler and handler[member] then a,b,c,d = handler[member](handler, info, ...) else error(format("Method %s doesn't exist in handler for type %s", member, membername)) end end del(info) return a,b,c,d else --The value isnt a function to call, return it return member end end --[[calls an options function that could be inherited, method name or function ref local function CallOptionsFunction(funcname ,option, options, path, appName, ...) local info = new() local func local group = options local handler --build the info table containing the path -- pick up functions while traversing the tree if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler for i, v in ipairs(path) do group = GetSubOption(group, v) info[i] = v if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler end info.options = options info[0] = appName info.arg = option.arg local a, b, c ,d if type(func) == "string" then if handler and handler[func] then a,b,c,d = handler[func](handler, info, ...) else error(string.format("Method %s doesn't exist in handler for type func", func)) end elseif type(func) == "function" then a,b,c,d = func(info, ...) end del(info) return a,b,c,d end --]] --tables to hold orders and names for options being sorted, will be created with new() --prevents needing to call functions repeatedly while sorting local tempOrders local tempNames local function compareOptions(a,b) if not a then return true end if not b then return false end local OrderA, OrderB = tempOrders[a] or 100, tempOrders[b] or 100 if OrderA == OrderB then local NameA = (type(tempNames[a]) == "string") and tempNames[a] or "" local NameB = (type(tempNames[b]) == "string") and tempNames[b] or "" return NameA:upper() < NameB:upper() end if OrderA < 0 then if OrderB >= 0 then return false end else if OrderB < 0 then return true end end return OrderA < OrderB end --builds 2 tables out of an options group -- keySort, sorted keys -- opts, combined options from .plugins and args local function BuildSortedOptionsTable(group, keySort, opts, options, path, appName) tempOrders = new() tempNames = new() if group.plugins then for plugin, t in pairs(group.plugins) do for k, v in pairs(t) do if not opts[k] then tinsert(keySort, k) opts[k] = v path[#path+1] = k tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName) tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName) path[#path] = nil end end end end for k, v in pairs(group.args) do if not opts[k] then tinsert(keySort, k) opts[k] = v path[#path+1] = k tempOrders[k] = GetOptionsMemberValue("order", v, options, path, appName) tempNames[k] = GetOptionsMemberValue("name", v, options, path, appName) path[#path] = nil end end tsort(keySort, compareOptions) del(tempOrders) del(tempNames) end local function DelTree(tree) if tree.children then local childs = tree.children for i = 1, #childs do DelTree(childs[i]) del(childs[i]) end del(childs) end end local function CleanUserData(widget, event) local user = widget:GetUserDataTable() if user.path then del(user.path) end if widget.type == "TreeGroup" then local tree = user.tree widget:SetTree(nil) if tree then for i = 1, #tree do DelTree(tree[i]) del(tree[i]) end del(tree) end end if widget.type == "TabGroup" then widget:SetTabs(nil) if user.tablist then del(user.tablist) end end if widget.type == "DropdownGroup" then widget:SetGroupList(nil) if user.grouplist then del(user.grouplist) end if user.orderlist then del(user.orderlist) end end end -- - Gets a status table for the given appname and options path. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param path The path to the options (a table with all group keys) -- @return function AceConfigDialog:GetStatusTable(appName, path) local status = self.Status if not status[appName] then status[appName] = {} status[appName].status = {} status[appName].children = {} end status = status[appName] if path then for i = 1, #path do local v = path[i] if not status.children[v] then status.children[v] = {} status.children[v].status = {} status.children[v].children = {} end status = status.children[v] end end return status.status end --- Selects the specified path in the options window. -- The path specified has to match the keys of the groups in the table. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param ... The path to the key that should be selected function AceConfigDialog:SelectGroup(appName, ...) local path = new() local app = reg:GetOptionsTable(appName) if not app then error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2) end local options = app("dialog", MAJOR) local group = options local status = self:GetStatusTable(appName, path) if not status.groups then status.groups = {} end status = status.groups local treevalue local treestatus for n = 1, select("#",...) do local key = select(n, ...) if group.childGroups == "tab" or group.childGroups == "select" then --if this is a tab or select group, select the group status.selected = key --children of this group are no longer extra levels of a tree treevalue = nil else --tree group by default if treevalue then --this is an extra level of a tree group, build a uniquevalue for it treevalue = treevalue.."\001"..key else --this is the top level of a tree group, the uniquevalue is the same as the key treevalue = key if not status.groups then status.groups = {} end --save this trees status table for any extra levels or groups treestatus = status end --make sure that the tree entry is open, and select it. --the selected group will be overwritten if a child is the final target but still needs to be open treestatus.selected = treevalue treestatus.groups[treevalue] = true end --move to the next group in the path group = GetSubOption(group, key) if not group then break end tinsert(path, key) status = self:GetStatusTable(appName, path) if not status.groups then status.groups = {} end status = status.groups end del(path) reg:NotifyChange(appName) end local function OptionOnMouseOver(widget, event) --show a tooltip/set the status bar to the desc text local user = widget:GetUserDataTable() local opt = user.option local options = user.options local path = user.path local appName = user.appName GameTooltip:SetOwner(widget.frame, "ANCHOR_TOPRIGHT") local name = GetOptionsMemberValue("name", opt, options, path, appName) local desc = GetOptionsMemberValue("desc", opt, options, path, appName) local usage = GetOptionsMemberValue("usage", opt, options, path, appName) local descStyle = opt.descStyle if descStyle and descStyle ~= "tooltip" then return end GameTooltip:SetText(name, 1, .82, 0, 1) if opt.type == "multiselect" then GameTooltip:AddLine(user.text,0.5, 0.5, 0.8, 1) end if type(desc) == "string" then GameTooltip:AddLine(desc, 1, 1, 1, 1) end if type(usage) == "string" then GameTooltip:AddLine("Usage: "..usage, NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, 1) end GameTooltip:Show() end local function OptionOnMouseLeave(widget, event) GameTooltip:Hide() end local function GetFuncName(option) local type = option.type if type == "execute" then return "func" else return "set" end end local function confirmPopup(appName, rootframe, basepath, info, message, func, ...) if not StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] then StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] = {} end local t = StaticPopupDialogs["ACECONFIGDIALOG30_CONFIRM_DIALOG"] for k in pairs(t) do t[k] = nil end t.text = message t.button1 = ACCEPT t.button2 = CANCEL t.preferredIndex = STATICPOPUP_NUMDIALOGS local dialog, oldstrata t.OnAccept = function() safecall(func, unpack(t)) if dialog and oldstrata then dialog:SetFrameStrata(oldstrata) end AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl)) del(info) end t.OnCancel = function() if dialog and oldstrata then dialog:SetFrameStrata(oldstrata) end AceConfigDialog:Open(appName, rootframe, unpack(basepath or emptyTbl)) del(info) end for i = 1, select("#", ...) do t[i] = select(i, ...) or false end t.timeout = 0 t.whileDead = 1 t.hideOnEscape = 1 dialog = StaticPopup_Show("ACECONFIGDIALOG30_CONFIRM_DIALOG") if dialog then oldstrata = dialog:GetFrameStrata() dialog:SetFrameStrata("TOOLTIP") end end local function validationErrorPopup(message) if not StaticPopupDialogs["ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG"] then StaticPopupDialogs["ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG"] = {} end local t = StaticPopupDialogs["ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG"] t.text = message t.button1 = OKAY t.preferredIndex = STATICPOPUP_NUMDIALOGS local dialog, oldstrata t.OnAccept = function() if dialog and oldstrata then dialog:SetFrameStrata(oldstrata) end end t.timeout = 0 t.whileDead = 1 t.hideOnEscape = 1 dialog = StaticPopup_Show("ACECONFIGDIALOG30_VALIDATION_ERROR_DIALOG") if dialog then oldstrata = dialog:GetFrameStrata() dialog:SetFrameStrata("TOOLTIP") end end local function ActivateControl(widget, event, ...) --This function will call the set / execute handler for the widget --widget:GetUserDataTable() contains the needed info local user = widget:GetUserDataTable() local option = user.option local options = user.options local path = user.path local info = new() local func local group = options local funcname = GetFuncName(option) local handler local confirm local validate --build the info table containing the path -- pick up functions while traversing the tree if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler confirm = group.confirm validate = group.validate for i = 1, #path do local v = path[i] group = GetSubOption(group, v) info[i] = v if group[funcname] ~= nil then func = group[funcname] end handler = group.handler or handler if group.confirm ~= nil then confirm = group.confirm end if group.validate ~= nil then validate = group.validate end end info.options = options info.appName = user.appName info.arg = option.arg info.handler = handler info.option = option info.type = option.type info.uiType = "dialog" info.uiName = MAJOR local name if type(option.name) == "function" then name = option.name(info) elseif type(option.name) == "string" then name = option.name else name = "" end local usage = option.usage local pattern = option.pattern local validated = true if option.type == "input" then if type(pattern)=="string" then if not strmatch(..., pattern) then validated = false end end end local success if validated and option.type ~= "execute" then if type(validate) == "string" then if handler and handler[validate] then success, validated = safecall(handler[validate], handler, info, ...) if not success then validated = false end else error(format("Method %s doesn't exist in handler for type execute", validate)) end elseif type(validate) == "function" then success, validated = safecall(validate, info, ...) if not success then validated = false end end end local rootframe = user.rootframe if not validated or type(validated) == "string" then if not validated then if usage then validated = name..": "..usage else if pattern then validated = name..": Expected "..pattern else validated = name..": Invalid Value" end end end -- show validate message if rootframe.SetStatusText then rootframe:SetStatusText(validated) else validationErrorPopup(validated) end PlaySound("igPlayerInviteDecline") del(info) return true else local confirmText = option.confirmText --call confirm func/method if type(confirm) == "string" then if handler and handler[confirm] then success, confirm = safecall(handler[confirm], handler, info, ...) if success and type(confirm) == "string" then confirmText = confirm confirm = true elseif not success then confirm = false end else error(format("Method %s doesn't exist in handler for type confirm", confirm)) end elseif type(confirm) == "function" then success, confirm = safecall(confirm, info, ...) if success and type(confirm) == "string" then confirmText = confirm confirm = true elseif not success then confirm = false end end --confirm if needed if type(confirm) == "boolean" then if confirm then if not confirmText then local name, desc = option.name, option.desc if type(name) == "function" then name = name(info) end if type(desc) == "function" then desc = desc(info) end confirmText = name if desc then confirmText = confirmText.." - "..desc end end local iscustom = user.rootframe:GetUserData("iscustom") local rootframe if iscustom then rootframe = user.rootframe end local basepath = user.rootframe:GetUserData("basepath") if type(func) == "string" then if handler and handler[func] then confirmPopup(user.appName, rootframe, basepath, info, confirmText, handler[func], handler, info, ...) else error(format("Method %s doesn't exist in handler for type func", func)) end elseif type(func) == "function" then confirmPopup(user.appName, rootframe, basepath, info, confirmText, func, info, ...) end --func will be called and info deleted when the confirm dialog is responded to return end end --call the function if type(func) == "string" then if handler and handler[func] then safecall(handler[func],handler, info, ...) else error(format("Method %s doesn't exist in handler for type func", func)) end elseif type(func) == "function" then safecall(func,info, ...) end local iscustom = user.rootframe:GetUserData("iscustom") local basepath = user.rootframe:GetUserData("basepath") or emptyTbl --full refresh of the frame, some controls dont cause this on all events if option.type == "color" then if event == "OnValueConfirmed" then if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end elseif option.type == "range" then if event == "OnMouseUp" then if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end --multiselects don't cause a refresh on 'OnValueChanged' only 'OnClosed' elseif option.type == "multiselect" then user.valuechanged = true else if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end end del(info) end local function ActivateSlider(widget, event, value) local option = widget:GetUserData("option") local min, max, step = option.min or (not option.softMin and 0 or nil), option.max or (not option.softMax and 100 or nil), option.step if min then if step then value = math_floor((value - min) / step + 0.5) * step + min end value = math_max(value, min) end if max then value = math_min(value, max) end ActivateControl(widget,event,value) end --called from a checkbox that is part of an internally created multiselect group --this type is safe to refresh on activation of one control local function ActivateMultiControl(widget, event, ...) ActivateControl(widget, event, widget:GetUserData("value"), ...) local user = widget:GetUserDataTable() local iscustom = user.rootframe:GetUserData("iscustom") local basepath = user.rootframe:GetUserData("basepath") or emptyTbl if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end local function MultiControlOnClosed(widget, event, ...) local user = widget:GetUserDataTable() if user.valuechanged then local iscustom = user.rootframe:GetUserData("iscustom") local basepath = user.rootframe:GetUserData("basepath") or emptyTbl if iscustom then AceConfigDialog:Open(user.appName, user.rootframe, unpack(basepath)) else AceConfigDialog:Open(user.appName, unpack(basepath)) end end end local function FrameOnClose(widget, event) local appName = widget:GetUserData("appName") AceConfigDialog.OpenFrames[appName] = nil gui:Release(widget) end local function CheckOptionHidden(option, options, path, appName) --check for a specific boolean option local hidden = pickfirstset(option.dialogHidden,option.guiHidden) if hidden ~= nil then return hidden end return GetOptionsMemberValue("hidden", option, options, path, appName) end local function CheckOptionDisabled(option, options, path, appName) --check for a specific boolean option local disabled = pickfirstset(option.dialogDisabled,option.guiDisabled) if disabled ~= nil then return disabled end return GetOptionsMemberValue("disabled", option, options, path, appName) end --[[ local function BuildTabs(group, options, path, appName) local tabs = new() local text = new() local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then tinsert(tabs, k) text[k] = GetOptionsMemberValue("name", v, options, path, appName) end path[#path] = nil end end del(keySort) del(opts) return tabs, text end ]] local function BuildSelect(group, options, path, appName) local groups = new() local order = new() local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then groups[k] = GetOptionsMemberValue("name", v, options, path, appName) tinsert(order, k) end path[#path] = nil end end del(opts) del(keySort) return groups, order end local function BuildSubGroups(group, tree, options, path, appName) local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then local entry = new() entry.value = k entry.text = GetOptionsMemberValue("name", v, options, path, appName) entry.icon = GetOptionsMemberValue("icon", v, options, path, appName) entry.iconCoords = GetOptionsMemberValue("iconCoords", v, options, path, appName) entry.disabled = CheckOptionDisabled(v, options, path, appName) if not tree.children then tree.children = new() end tinsert(tree.children,entry) if (v.childGroups or "tree") == "tree" then BuildSubGroups(v,entry, options, path, appName) end end path[#path] = nil end end del(keySort) del(opts) end local function BuildGroups(group, options, path, appName, recurse) local tree = new() local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] if v.type == "group" then path[#path+1] = k local inline = pickfirstset(v.dialogInline,v.guiInline,v.inline, false) local hidden = CheckOptionHidden(v, options, path, appName) if not inline and not hidden then local entry = new() entry.value = k entry.text = GetOptionsMemberValue("name", v, options, path, appName) entry.icon = GetOptionsMemberValue("icon", v, options, path, appName) entry.iconCoords = GetOptionsMemberValue("iconCoords", v, options, path, appName) entry.disabled = CheckOptionDisabled(v, options, path, appName) tinsert(tree,entry) if recurse and (v.childGroups or "tree") == "tree" then BuildSubGroups(v,entry, options, path, appName) end end path[#path] = nil end end del(keySort) del(opts) return tree end local function InjectInfo(control, options, option, path, rootframe, appName) local user = control:GetUserDataTable() for i = 1, #path do user[i] = path[i] end user.rootframe = rootframe user.option = option user.options = options user.path = copy(path) user.appName = appName control:SetCallback("OnRelease", CleanUserData) control:SetCallback("OnLeave", OptionOnMouseLeave) control:SetCallback("OnEnter", OptionOnMouseOver) end local function CreateControl(userControlType, fallbackControlType) local control if userControlType then control = gui:Create(userControlType) if not control then geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(userControlType))) end end if not control then control = gui:Create(fallbackControlType) end return control end local function sortTblAsStrings(x,y) return tostring(x) < tostring(y) -- Support numbers as keys end --[[ options - root of the options table being fed container - widget that controls will be placed in rootframe - Frame object the options are in path - table with the keys to get to the group being fed --]] local function FeedOptions(appName, options,container,rootframe,path,group,inline) local keySort = new() local opts = new() BuildSortedOptionsTable(group, keySort, opts, options, path, appName) for i = 1, #keySort do local k = keySort[i] local v = opts[k] tinsert(path, k) local hidden = CheckOptionHidden(v, options, path, appName) local name = GetOptionsMemberValue("name", v, options, path, appName) if not hidden then if v.type == "group" then if inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) then --Inline group local GroupContainer if name and name ~= "" then GroupContainer = gui:Create("InlineGroup") GroupContainer:SetTitle(name or "") else GroupContainer = gui:Create("SimpleGroup") end GroupContainer.width = "fill" GroupContainer:SetLayout("flow") container:AddChild(GroupContainer) FeedOptions(appName,options,GroupContainer,rootframe,path,v,true) end else --Control to feed local control local name = GetOptionsMemberValue("name", v, options, path, appName) if v.type == "execute" then local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName) local image, width, height = GetOptionsMemberValue("image",v, options, path, appName) local iconControl = type(image) == "string" or type(image) == "number" control = CreateControl(v.dialogControl or v.control, iconControl and "Icon" or "Button") if iconControl then if not width then width = GetOptionsMemberValue("imageWidth",v, options, path, appName) end if not height then height = GetOptionsMemberValue("imageHeight",v, options, path, appName) end if type(imageCoords) == "table" then control:SetImage(image, unpack(imageCoords)) else control:SetImage(image) end if type(width) ~= "number" then width = 32 end if type(height) ~= "number" then height = 32 end control:SetImageSize(width, height) control:SetLabel(name) else control:SetText(name) end control:SetCallback("OnClick",ActivateControl) elseif v.type == "input" then control = CreateControl(v.dialogControl or v.control, v.multiline and "MultiLineEditBox" or "EditBox") if v.multiline and control.SetNumLines then control:SetNumLines(tonumber(v.multiline) or 4) end control:SetLabel(name) control:SetCallback("OnEnterPressed",ActivateControl) local text = GetOptionsMemberValue("get",v, options, path, appName) if type(text) ~= "string" then text = "" end control:SetText(text) elseif v.type == "toggle" then control = CreateControl(v.dialogControl or v.control, "CheckBox") control:SetLabel(name) control:SetTriState(v.tristate) local value = GetOptionsMemberValue("get",v, options, path, appName) control:SetValue(value) control:SetCallback("OnValueChanged",ActivateControl) if v.descStyle == "inline" then local desc = GetOptionsMemberValue("desc", v, options, path, appName) control:SetDescription(desc) end local image = GetOptionsMemberValue("image", v, options, path, appName) local imageCoords = GetOptionsMemberValue("imageCoords", v, options, path, appName) if type(image) == "string" or type(image) == "number" then if type(imageCoords) == "table" then control:SetImage(image, unpack(imageCoords)) else control:SetImage(image) end end elseif v.type == "range" then control = CreateControl(v.dialogControl or v.control, "Slider") control:SetLabel(name) control:SetSliderValues(v.softMin or v.min or 0, v.softMax or v.max or 100, v.bigStep or v.step or 0) control:SetIsPercent(v.isPercent) local value = GetOptionsMemberValue("get",v, options, path, appName) if type(value) ~= "number" then value = 0 end control:SetValue(value) control:SetCallback("OnValueChanged",ActivateSlider) control:SetCallback("OnMouseUp",ActivateSlider) elseif v.type == "select" then local values = GetOptionsMemberValue("values", v, options, path, appName) local sorting = GetOptionsMemberValue("sorting", v, options, path, appName) if v.style == "radio" then local disabled = CheckOptionDisabled(v, options, path, appName) local width = GetOptionsMemberValue("width",v,options,path,appName) control = gui:Create("InlineGroup") control:SetLayout("Flow") control:SetTitle(name) control.width = "fill" control:PauseLayout() local optionValue = GetOptionsMemberValue("get",v, options, path, appName) if not sorting then sorting = {} for value, text in pairs(values) do sorting[#sorting+1]=value end tsort(sorting, sortTblAsStrings) end for k, value in ipairs(sorting) do local text = values[value] local radio = gui:Create("CheckBox") radio:SetLabel(text) radio:SetUserData("value", value) radio:SetUserData("text", text) radio:SetDisabled(disabled) radio:SetType("radio") radio:SetValue(optionValue == value) radio:SetCallback("OnValueChanged", ActivateMultiControl) InjectInfo(radio, options, v, path, rootframe, appName) control:AddChild(radio) if width == "double" then radio:SetWidth(width_multiplier * 2) elseif width == "half" then radio:SetWidth(width_multiplier / 2) elseif (type(width) == "number") then radio:SetWidth(width_multiplier * width) elseif width == "full" then radio.width = "fill" else radio:SetWidth(width_multiplier) end end control:ResumeLayout() control:DoLayout() else control = CreateControl(v.dialogControl or v.control, "Dropdown") local itemType = v.itemControl if itemType and not gui:GetWidgetVersion(itemType) then geterrorhandler()(("Invalid Custom Item Type - %s"):format(tostring(itemType))) itemType = nil end control:SetLabel(name) control:SetList(values, sorting, itemType) local value = GetOptionsMemberValue("get",v, options, path, appName) if not values[value] then value = nil end control:SetValue(value) control:SetCallback("OnValueChanged", ActivateControl) end elseif v.type == "multiselect" then local values = GetOptionsMemberValue("values", v, options, path, appName) local disabled = CheckOptionDisabled(v, options, path, appName) local valuesort = new() if values then for value, text in pairs(values) do tinsert(valuesort, value) end end tsort(valuesort) local controlType = v.dialogControl or v.control if controlType then control = gui:Create(controlType) if not control then geterrorhandler()(("Invalid Custom Control Type - %s"):format(tostring(controlType))) end end if control then control:SetMultiselect(true) control:SetLabel(name) control:SetList(values) control:SetDisabled(disabled) control:SetCallback("OnValueChanged",ActivateControl) control:SetCallback("OnClosed", MultiControlOnClosed) local width = GetOptionsMemberValue("width",v,options,path,appName) if width == "double" then control:SetWidth(width_multiplier * 2) elseif width == "half" then control:SetWidth(width_multiplier / 2) elseif (type(width) == "number") then control:SetWidth(width_multiplier * width) elseif width == "full" then control.width = "fill" else control:SetWidth(width_multiplier) end --check:SetTriState(v.tristate) for i = 1, #valuesort do local key = valuesort[i] local value = GetOptionsMemberValue("get",v, options, path, appName, key) control:SetItemValue(key,value) end else control = gui:Create("InlineGroup") control:SetLayout("Flow") control:SetTitle(name) control.width = "fill" control:PauseLayout() local width = GetOptionsMemberValue("width",v,options,path,appName) for i = 1, #valuesort do local value = valuesort[i] local text = values[value] local check = gui:Create("CheckBox") check:SetLabel(text) check:SetUserData("value", value) check:SetUserData("text", text) check:SetDisabled(disabled) check:SetTriState(v.tristate) check:SetValue(GetOptionsMemberValue("get",v, options, path, appName, value)) check:SetCallback("OnValueChanged",ActivateMultiControl) InjectInfo(check, options, v, path, rootframe, appName) control:AddChild(check) if width == "double" then check:SetWidth(width_multiplier * 2) elseif width == "half" then check:SetWidth(width_multiplier / 2) elseif (type(width) == "number") then check:SetWidth(width_multiplier * width) elseif width == "full" then check.width = "fill" else check:SetWidth(width_multiplier) end end control:ResumeLayout() control:DoLayout() end del(valuesort) elseif v.type == "color" then control = CreateControl(v.dialogControl or v.control, "ColorPicker") control:SetLabel(name) control:SetHasAlpha(GetOptionsMemberValue("hasAlpha",v, options, path, appName)) control:SetColor(GetOptionsMemberValue("get",v, options, path, appName)) control:SetCallback("OnValueChanged",ActivateControl) control:SetCallback("OnValueConfirmed",ActivateControl) elseif v.type == "keybinding" then control = CreateControl(v.dialogControl or v.control, "Keybinding") control:SetLabel(name) control:SetKey(GetOptionsMemberValue("get",v, options, path, appName)) control:SetCallback("OnKeyChanged",ActivateControl) elseif v.type == "header" then control = CreateControl(v.dialogControl or v.control, "Heading") control:SetText(name) control.width = "fill" elseif v.type == "description" then control = CreateControl(v.dialogControl or v.control, "Label") control:SetText(name) local fontSize = GetOptionsMemberValue("fontSize",v, options, path, appName) if fontSize == "medium" then control:SetFontObject(GameFontHighlight) elseif fontSize == "large" then control:SetFontObject(GameFontHighlightLarge) else -- small or invalid control:SetFontObject(GameFontHighlightSmall) end local imageCoords = GetOptionsMemberValue("imageCoords",v, options, path, appName) local image, width, height = GetOptionsMemberValue("image",v, options, path, appName) if type(image) == "string" then if not width then width = GetOptionsMemberValue("imageWidth",v, options, path, appName) end if not height then height = GetOptionsMemberValue("imageHeight",v, options, path, appName) end if type(imageCoords) == "table" then control:SetImage(image, unpack(imageCoords)) else control:SetImage(image) end if type(width) ~= "number" then width = 32 end if type(height) ~= "number" then height = 32 end control:SetImageSize(width, height) end local width = GetOptionsMemberValue("width",v,options,path,appName) control.width = not width and "fill" end --Common Init if control then if control.width ~= "fill" then local width = GetOptionsMemberValue("width",v,options,path,appName) if width == "double" then control:SetWidth(width_multiplier * 2) elseif width == "half" then control:SetWidth(width_multiplier / 2) elseif (type(width) == "number") then control:SetWidth(width_multiplier * width) elseif width == "full" then control.width = "fill" else control:SetWidth(width_multiplier) end end if control.SetDisabled then local disabled = CheckOptionDisabled(v, options, path, appName) control:SetDisabled(disabled) end InjectInfo(control, options, v, path, rootframe, appName) container:AddChild(control) end end end tremove(path) end container:ResumeLayout() container:DoLayout() del(keySort) del(opts) end local function BuildPath(path, ...) for i = 1, select("#",...) do tinsert(path, (select(i,...))) end end local function TreeOnButtonEnter(widget, event, uniquevalue, button) local user = widget:GetUserDataTable() if not user then return end local options = user.options local option = user.option local path = user.path local appName = user.appName local feedpath = new() for i = 1, #path do feedpath[i] = path[i] end BuildPath(feedpath, ("\001"):split(uniquevalue)) local group = options for i = 1, #feedpath do if not group then return end group = GetSubOption(group, feedpath[i]) end local name = GetOptionsMemberValue("name", group, options, feedpath, appName) local desc = GetOptionsMemberValue("desc", group, options, feedpath, appName) GameTooltip:SetOwner(button, "ANCHOR_NONE") if widget.type == "TabGroup" then GameTooltip:SetPoint("BOTTOM",button,"TOP") else GameTooltip:SetPoint("LEFT",button,"RIGHT") end GameTooltip:SetText(name, 1, .82, 0, 1) if type(desc) == "string" then GameTooltip:AddLine(desc, 1, 1, 1, 1) end GameTooltip:Show() end local function TreeOnButtonLeave(widget, event, value, button) GameTooltip:Hide() end local function GroupExists(appName, options, path, uniquevalue) if not uniquevalue then return false end local feedpath = new() local temppath = new() for i = 1, #path do feedpath[i] = path[i] end BuildPath(feedpath, ("\001"):split(uniquevalue)) local group = options for i = 1, #feedpath do local v = feedpath[i] temppath[i] = v group = GetSubOption(group, v) if not group or group.type ~= "group" or CheckOptionHidden(group, options, temppath, appName) then del(feedpath) del(temppath) return false end end del(feedpath) del(temppath) return true end local function GroupSelected(widget, event, uniquevalue) local user = widget:GetUserDataTable() local options = user.options local option = user.option local path = user.path local rootframe = user.rootframe local feedpath = new() for i = 1, #path do feedpath[i] = path[i] end BuildPath(feedpath, ("\001"):split(uniquevalue)) widget:ReleaseChildren() AceConfigDialog:FeedGroup(user.appName,options,widget,rootframe,feedpath) del(feedpath) end --[[ -- INTERNAL -- This function will feed one group, and any inline child groups into the given container Select Groups will only have the selection control (tree, tabs, dropdown) fed in and have a group selected, this event will trigger the feeding of child groups Rules: If the group is Inline, FeedOptions If the group has no child groups, FeedOptions If the group is a tab or select group, FeedOptions then add the Group Control If the group is a tree group FeedOptions then its parent isnt a tree group: then add the tree control containing this and all child tree groups if its parent is a tree group, its already a node on a tree --]] function AceConfigDialog:FeedGroup(appName,options,container,rootframe,path, isRoot) local group = options --follow the path to get to the curent group local inline local grouptype, parenttype = options.childGroups, "none" for i = 1, #path do local v = path[i] group = GetSubOption(group, v) inline = inline or pickfirstset(v.dialogInline,v.guiInline,v.inline, false) parenttype = grouptype grouptype = group.childGroups end if not parenttype then parenttype = "tree" end --check if the group has child groups local hasChildGroups for k, v in pairs(group.args) do if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then hasChildGroups = true end end if group.plugins then for plugin, t in pairs(group.plugins) do for k, v in pairs(t) do if v.type == "group" and not pickfirstset(v.dialogInline,v.guiInline,v.inline, false) and not CheckOptionHidden(v, options, path, appName) then hasChildGroups = true end end end end container:SetLayout("flow") local scroll --Add a scrollframe if we are not going to add a group control, this is the inverse of the conditions for that later on if (not (hasChildGroups and not inline)) or (grouptype ~= "tab" and grouptype ~= "select" and (parenttype == "tree" and not isRoot)) then if container.type ~= "InlineGroup" and container.type ~= "SimpleGroup" then scroll = gui:Create("ScrollFrame") scroll:SetLayout("flow") scroll.width = "fill" scroll.height = "fill" container:SetLayout("fill") container:AddChild(scroll) container = scroll end end FeedOptions(appName,options,container,rootframe,path,group,nil) if scroll then container:PerformLayout() local status = self:GetStatusTable(appName, path) if not status.scroll then status.scroll = {} end scroll:SetStatusTable(status.scroll) end if hasChildGroups and not inline then local name = GetOptionsMemberValue("name", group, options, path, appName) if grouptype == "tab" then local tab = gui:Create("TabGroup") InjectInfo(tab, options, group, path, rootframe, appName) tab:SetCallback("OnGroupSelected", GroupSelected) tab:SetCallback("OnTabEnter", TreeOnButtonEnter) tab:SetCallback("OnTabLeave", TreeOnButtonLeave) local status = AceConfigDialog:GetStatusTable(appName, path) if not status.groups then status.groups = {} end tab:SetStatusTable(status.groups) tab.width = "fill" tab.height = "fill" local tabs = BuildGroups(group, options, path, appName) tab:SetTabs(tabs) tab:SetUserData("tablist", tabs) for i = 1, #tabs do local entry = tabs[i] if not entry.disabled then tab:SelectTab((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value) break end end container:AddChild(tab) elseif grouptype == "select" then local select = gui:Create("DropdownGroup") select:SetTitle(name) InjectInfo(select, options, group, path, rootframe, appName) select:SetCallback("OnGroupSelected", GroupSelected) local status = AceConfigDialog:GetStatusTable(appName, path) if not status.groups then status.groups = {} end select:SetStatusTable(status.groups) local grouplist, orderlist = BuildSelect(group, options, path, appName) select:SetGroupList(grouplist, orderlist) select:SetUserData("grouplist", grouplist) select:SetUserData("orderlist", orderlist) local firstgroup = orderlist[1] if firstgroup then select:SetGroup((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or firstgroup) end select.width = "fill" select.height = "fill" container:AddChild(select) --assume tree group by default --if parenttype is tree then this group is already a node on that tree elseif (parenttype ~= "tree") or isRoot then local tree = gui:Create("TreeGroup") InjectInfo(tree, options, group, path, rootframe, appName) tree:EnableButtonTooltips(false) tree.width = "fill" tree.height = "fill" tree:SetCallback("OnGroupSelected", GroupSelected) tree:SetCallback("OnButtonEnter", TreeOnButtonEnter) tree:SetCallback("OnButtonLeave", TreeOnButtonLeave) local status = AceConfigDialog:GetStatusTable(appName, path) if not status.groups then status.groups = {} end local treedefinition = BuildGroups(group, options, path, appName, true) tree:SetStatusTable(status.groups) tree:SetTree(treedefinition) tree:SetUserData("tree",treedefinition) for i = 1, #treedefinition do local entry = treedefinition[i] if not entry.disabled then tree:SelectByValue((GroupExists(appName, options, path,status.groups.selected) and status.groups.selected) or entry.value) break end end container:AddChild(tree) end end end local old_CloseSpecialWindows local function RefreshOnUpdate(this) for appName in pairs(this.closing) do if AceConfigDialog.OpenFrames[appName] then AceConfigDialog.OpenFrames[appName]:Hide() end if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do if not widget:IsVisible() then widget:ReleaseChildren() end end end this.closing[appName] = nil end if this.closeAll then for k, v in pairs(AceConfigDialog.OpenFrames) do if not this.closeAllOverride[k] then v:Hide() end end this.closeAll = nil wipe(this.closeAllOverride) end for appName in pairs(this.apps) do if AceConfigDialog.OpenFrames[appName] then local user = AceConfigDialog.OpenFrames[appName]:GetUserDataTable() AceConfigDialog:Open(appName, unpack(user.basepath or emptyTbl)) end if AceConfigDialog.BlizOptions and AceConfigDialog.BlizOptions[appName] then for key, widget in pairs(AceConfigDialog.BlizOptions[appName]) do local user = widget:GetUserDataTable() if widget:IsVisible() then AceConfigDialog:Open(widget:GetUserData("appName"), widget, unpack(user.basepath or emptyTbl)) end end end this.apps[appName] = nil end this:SetScript("OnUpdate", nil) end -- Upgrade the OnUpdate script as well, if needed. if AceConfigDialog.frame:GetScript("OnUpdate") then AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) end --- Close all open options windows function AceConfigDialog:CloseAll() AceConfigDialog.frame.closeAll = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) if next(self.OpenFrames) then return true end end --- Close a specific options window. -- @param appName The application name as given to `:RegisterOptionsTable()` function AceConfigDialog:Close(appName) if self.OpenFrames[appName] then AceConfigDialog.frame.closing[appName] = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) return true end end -- Internal -- Called by AceConfigRegistry function AceConfigDialog:ConfigTableChanged(event, appName) AceConfigDialog.frame.apps[appName] = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) end reg.RegisterCallback(AceConfigDialog, "ConfigTableChange", "ConfigTableChanged") --- Sets the default size of the options window for a specific application. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param width The default width -- @param height The default height function AceConfigDialog:SetDefaultSize(appName, width, height) local status = AceConfigDialog:GetStatusTable(appName) if type(width) == "number" and type(height) == "number" then status.width = width status.height = height end end --- Open an option window at the specified path (if any). -- This function can optionally feed the group into a pre-created container -- instead of creating a new container frame. -- @paramsig appName [, container][, ...] -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param container An optional container frame to feed the options into -- @param ... The path to open after creating the options window (see `:SelectGroup` for details) function AceConfigDialog:Open(appName, container, ...) if not old_CloseSpecialWindows then old_CloseSpecialWindows = CloseSpecialWindows CloseSpecialWindows = function() local found = old_CloseSpecialWindows() return self:CloseAll() or found end end local app = reg:GetOptionsTable(appName) if not app then error(("%s isn't registed with AceConfigRegistry, unable to open config"):format(appName), 2) end local options = app("dialog", MAJOR) local f local path = new() local name = GetOptionsMemberValue("name", options, options, path, appName) --If an optional path is specified add it to the path table before feeding the options --as container is optional as well it may contain the first element of the path if type(container) == "string" then tinsert(path, container) container = nil end for n = 1, select("#",...) do tinsert(path, (select(n, ...))) end local option = options if type(container) == "table" and container.type == "BlizOptionsGroup" and #path > 0 then for i = 1, #path do option = options.args[path[i]] end name = format("%s - %s", name, GetOptionsMemberValue("name", option, options, path, appName)) end --if a container is given feed into that if container then f = container f:ReleaseChildren() f:SetUserData("appName", appName) f:SetUserData("iscustom", true) if #path > 0 then f:SetUserData("basepath", copy(path)) end local status = AceConfigDialog:GetStatusTable(appName) if not status.width then status.width = 700 end if not status.height then status.height = 500 end if f.SetStatusTable then f:SetStatusTable(status) end if f.SetTitle then f:SetTitle(name or "") end else if not self.OpenFrames[appName] then f = gui:Create("Frame") self.OpenFrames[appName] = f else f = self.OpenFrames[appName] end f:ReleaseChildren() f:SetCallback("OnClose", FrameOnClose) f:SetUserData("appName", appName) if #path > 0 then f:SetUserData("basepath", copy(path)) end f:SetTitle(name or "") local status = AceConfigDialog:GetStatusTable(appName) f:SetStatusTable(status) end self:FeedGroup(appName,options,f,f,path,true) if f.Show then f:Show() end del(path) if AceConfigDialog.frame.closeAll then -- close all is set, but thats not good, since we're just opening here, so force it AceConfigDialog.frame.closeAllOverride[appName] = true end end -- convert pre-39 BlizOptions structure to the new format if oldminor and oldminor < 39 and AceConfigDialog.BlizOptions then local old = AceConfigDialog.BlizOptions local new = {} for key, widget in pairs(old) do local appName = widget:GetUserData("appName") if not new[appName] then new[appName] = {} end new[appName][key] = widget end AceConfigDialog.BlizOptions = new else AceConfigDialog.BlizOptions = AceConfigDialog.BlizOptions or {} end local function FeedToBlizPanel(widget, event) local path = widget:GetUserData("path") AceConfigDialog:Open(widget:GetUserData("appName"), widget, unpack(path or emptyTbl)) end local function ClearBlizPanel(widget, event) local appName = widget:GetUserData("appName") AceConfigDialog.frame.closing[appName] = true AceConfigDialog.frame:SetScript("OnUpdate", RefreshOnUpdate) end --- Add an option table into the Blizzard Interface Options panel. -- You can optionally supply a descriptive name to use and a parent frame to use, -- as well as a path in the options table.\\ -- If no name is specified, the appName will be used instead. -- -- If you specify a proper `parent` (by name), the interface options will generate a -- tree layout. Note that only one level of children is supported, so the parent always -- has to be a head-level note. -- -- This function returns a reference to the container frame registered with the Interface -- Options. You can use this reference to open the options with the API function -- `InterfaceOptionsFrame_OpenToCategory`. -- @param appName The application name as given to `:RegisterOptionsTable()` -- @param name A descriptive name to display in the options tree (defaults to appName) -- @param parent The parent to use in the interface options tree. -- @param ... The path in the options table to feed into the interface options panel. -- @return The reference to the frame registered into the Interface Options. function AceConfigDialog:AddToBlizOptions(appName, name, parent, ...) local BlizOptions = AceConfigDialog.BlizOptions local key = appName for n = 1, select("#", ...) do key = key.."\001"..select(n, ...) end if not BlizOptions[appName] then BlizOptions[appName] = {} end if not BlizOptions[appName][key] then local group = gui:Create("BlizOptionsGroup") BlizOptions[appName][key] = group group:SetName(name or appName, parent) group:SetTitle(name or appName) group:SetUserData("appName", appName) if select("#", ...) > 0 then local path = {} for n = 1, select("#",...) do tinsert(path, (select(n, ...))) end group:SetUserData("path", path) end group:SetCallback("OnShow", FeedToBlizPanel) group:SetCallback("OnHide", ClearBlizPanel) InterfaceOptions_AddCategory(group.frame) return group.frame else error(("%s has already been added to the Blizzard Options Window with the given path"):format(appName), 2) end end
0
0.955188
1
0.955188
game-dev
MEDIA
0.399145
game-dev
0.941037
1
0.941037
openai/doom-py
7,104
doom_py/src/vizdoom/src/g_shared/a_randomspawner.cpp
/* ** a_randomspawner.cpp ** A thing that randomly spawns one item in a list of many, before disappearing. ** bouncecount is used to keep track of recursions (so as to prevent infinite loops). ** Species is used to store the index of the spawned actor's name. */ #include "actor.h" #include "info.h" #include "m_random.h" #include "p_local.h" #include "p_enemy.h" #include "s_sound.h" #include "statnums.h" #include "gstrings.h" #include "a_action.h" #include "thingdef/thingdef.h" #include "v_text.h" #define MAX_RANDOMSPAWNERS_RECURSION 32 // Should be largely more than enough, honestly. static FRandom pr_randomspawn("RandomSpawn"); static bool IsMonster(const FDropItem *di) { const PClass *pclass = PClass::FindClass(di->Name); if (NULL == pclass) { return false; } return 0 != (GetDefaultByType(pclass)->flags3 & MF3_ISMONSTER); } class ARandomSpawner : public AActor { DECLARE_CLASS (ARandomSpawner, AActor) // To handle "RandomSpawning" missiles, the code has to be split in two parts. // If the following code is not done in BeginPlay, missiles will use the // random spawner's velocity (0...) instead of their own. void BeginPlay() { FDropItem *di; // di will be our drop item list iterator FDropItem *drop; // while drop stays as the reference point. int n=0; bool nomonsters = (dmflags & DF_NO_MONSTERS) || (level.flags2 & LEVEL2_NOMONSTERS); Super::BeginPlay(); drop = di = GetDropItems(); if (di != NULL) { while (di != NULL) { if (di->Name != NAME_None) { if (!nomonsters || !IsMonster(di)) { if (di->amount < 0) di->amount = 1; // default value is -1, we need a positive value. n += di->amount; // this is how we can weight the list. } di = di->Next; } } if (n == 0) { // Nothing left to spawn. They must have all been monsters, and monsters are disabled. Destroy(); return; } // Then we reset the iterator to the start position... di = drop; // Take a random number... n = pr_randomspawn(n); // And iterate in the array up to the random number chosen. while (n > -1 && di != NULL) { if (di->Name != NAME_None && (!nomonsters || !IsMonster(di))) { n -= di->amount; if ((di->Next != NULL) && (n > -1)) di = di->Next; else n = -1; } else { di = di->Next; } } // So now we can spawn the dropped item. if (di == NULL || bouncecount >= MAX_RANDOMSPAWNERS_RECURSION) // Prevents infinite recursions { Spawn("Unknown", Pos(), NO_REPLACE); // Show that there's a problem. Destroy(); return; } else if (pr_randomspawn() <= di->probability) // prob 255 = always spawn, prob 0 = never spawn. { // Handle replacement here so as to get the proper speed and flags for missiles const PClass *cls; cls = PClass::FindClass(di->Name); if (cls != NULL) { const PClass *rep = cls->GetReplacement(); if (rep != NULL) { cls = rep; } } if (cls != NULL) { Species = cls->TypeName; AActor *defmobj = GetDefaultByType(cls); this->Speed = defmobj->Speed; this->flags |= (defmobj->flags & MF_MISSILE); this->flags2 |= (defmobj->flags2 & MF2_SEEKERMISSILE); this->flags4 |= (defmobj->flags4 & MF4_SPECTRAL); } else { Printf(TEXTCOLOR_RED "Unknown item class %s to drop from a random spawner\n", di->Name.GetChars()); Species = NAME_None; } } } } // The second half of random spawning. Now that the spawner is initialized, the // real actor can be created. If the following code were in BeginPlay instead, // missiles would not have yet obtained certain information that is absolutely // necessary to them -- such as their source and destination. void PostBeginPlay() { AActor * newmobj = NULL; bool boss = false; Super::PostBeginPlay(); if (Species == NAME_None) { Destroy(); return; } const PClass * cls = PClass::FindClass(Species); if (this->flags & MF_MISSILE && target && target->target) // Attempting to spawn a missile. { if ((tracer == NULL) && (flags2 & MF2_SEEKERMISSILE)) tracer = target->target; newmobj = P_SpawnMissileXYZ(Pos(), target, target->target, cls, false); } else newmobj = Spawn(cls, Pos(), NO_REPLACE); if (newmobj != NULL) { // copy everything relevant newmobj->SpawnAngle = newmobj->angle = angle; newmobj->SpawnPoint[2] = SpawnPoint[2]; newmobj->special = special; newmobj->args[0] = args[0]; newmobj->args[1] = args[1]; newmobj->args[2] = args[2]; newmobj->args[3] = args[3]; newmobj->args[4] = args[4]; newmobj->special1 = special1; newmobj->special2 = special2; newmobj->SpawnFlags = SpawnFlags & ~MTF_SECRET; // MTF_SECRET needs special treatment to avoid incrementing the secret counter twice. It had already been processed for the spawner itself. newmobj->HandleSpawnFlags(); newmobj->SpawnFlags = SpawnFlags; newmobj->tid = tid; newmobj->AddToHash(); newmobj->velx = velx; newmobj->vely = vely; newmobj->velz = velz; newmobj->master = master; // For things such as DamageMaster/DamageChildren, transfer mastery. newmobj->target = target; newmobj->tracer = tracer; newmobj->CopyFriendliness(this, false); // This handles things such as projectiles with the MF4_SPECTRAL flag that have // a health set to -2 after spawning, for internal reasons. if (health != SpawnHealth()) newmobj->health = health; if (!(flags & MF_DROPPED)) newmobj->flags &= ~MF_DROPPED; // Handle special altitude flags if (newmobj->flags & MF_SPAWNCEILING) { newmobj->SetZ(newmobj->ceilingz - newmobj->height - SpawnPoint[2]); } else if (newmobj->flags2 & MF2_SPAWNFLOAT) { fixed_t space = newmobj->ceilingz - newmobj->height - newmobj->floorz; if (space > 48*FRACUNIT) { space -= 40*FRACUNIT; newmobj->SetZ(MulScale8 (space, pr_randomspawn()) + newmobj->floorz + 40*FRACUNIT); } newmobj->AddZ(SpawnPoint[2]); } if (newmobj->flags & MF_MISSILE) P_CheckMissileSpawn(newmobj, 0); // Bouncecount is used to count how many recursions we're in. if (newmobj->IsKindOf(PClass::FindClass("RandomSpawner"))) newmobj->bouncecount = ++bouncecount; // If the spawned actor has either of those flags, it's a boss. if ((newmobj->flags4 & MF4_BOSSDEATH) || (newmobj->flags2 & MF2_BOSS)) boss = true; // If a replaced actor has either of those same flags, it's also a boss. AActor * rep = GetDefaultByType(GetClass()->ActorInfo->GetReplacee()->Class); if (rep && ((rep->flags4 & MF4_BOSSDEATH) || (rep->flags2 & MF2_BOSS))) boss = true; } if (boss) this->tracer = newmobj; else // "else" because a boss-replacing spawner must wait until it can call A_BossDeath. Destroy(); } void Tick() // This function is needed for handling boss replacers { Super::Tick(); if (tracer == NULL || tracer->health <= 0) { CALL_ACTION(A_BossDeath, this); Destroy(); } } }; IMPLEMENT_CLASS (ARandomSpawner)
0
0.683977
1
0.683977
game-dev
MEDIA
0.973954
game-dev
0.966375
1
0.966375
GardensOfKadesh/Homeworld
174,079
src/Game/Sensors.c
/*============================================================================= Name : Sensors.c Purpose : Code for handling and rendering the sensors manager. Created 10/8/1997 by lmoloney Copyright Relic Entertainment, Inc. All rights reserved. =============================================================================*/ #include "Sensors.h" #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "Alliance.h" #include "Battle.h" #include "Blobs.h" #include "Bounties.h" #include "BTG.h" #include "Camera.h" #include "CameraCommand.h" #include "CommandDefs.h" #include "CommandWrap.h" #include "Debug.h" #include "FastMath.h" #include "font.h" #include "glinc.h" #include "GravWellGenerator.h" #include "InfoOverlay.h" #include "Light.h" #include "main.h" #include "mainrgn.h" #include "Memory.h" #include "mouse.h" #include "MultiplayerGame.h" #include "NIS.h" #include "PiePlate.h" #include "Ping.h" #include "prim2d.h" #include "prim3d.h" #include "Probe.h" #include "ProximitySensor.h" #include "Randy.h" #include "Region.h" #include "render.h" #include "rglu.h" #include "SaveGame.h" #include "Select.h" #include "Shader.h" #include "ShipSelect.h" #include "SinglePlayer.h" #include "SoundEvent.h" #include "SoundEventDefs.h" #include "StatScript.h" #include "StringSupport.h" #include "Subtitle.h" #include "Tactical.h" #include "TaskBar.h" #include "Teams.h" #include "Transformer.h" #include "Tutor.h" #include "Tweak.h" #include "Universe.h" #include "UnivUpdate.h" #include "utility.h" #include "Vector.h" #if defined _MSC_VER #define isnan(x) _isnan(x) #endif //located in mainrg.c //falko's fault...not mine..long story void toFieldSphereDraw(ShipPtr ship,real32 radius, real32 scale, color passedColour); void (*smHoldLeft)(void); void (*smHoldRight)(void); #if SM_TOGGLE_SENSOR_LEVEL void smToggleSensorsLevel(void); #endif /*============================================================================= Data: =============================================================================*/ //set this to TRUE if you want it to be the Fleet Intel version of the SM bool32 smFleetIntel = FALSE; //toggles for what to display Camera smCamera; Camera smTempCamera; sdword smTacticalOverlay = FALSE; sdword smResources = TRUE; sdword smNonResources = TRUE; bool32 smFocusOnMothershipOnClose = FALSE; //arrays of stars for quick star rendering extern ubyte* stararray; extern color HorseRaceDropoutColor; //region handle for the sensors manager viewport regionhandle smViewportRegion; regionhandle smBaseRegion; rectangle smViewRectangle; sdword smClicking = FALSE; //table of functions to draw a mission sphere at varying levels of visibility void smSelectHold(void); //point specification stuffs /* sdword smPointSpecMode = SPM_Idle; sdword smCrosshairSize = SM_CrosshairSize; sdword smMousePauseX; sdword smMousePauseY; */ //colors for differing sphere statuses color spcNormal = SPC_Normal; color spcSelected = SPC_Selected; color spcTeamColor= SPC_TeamColor; // color for printing the A for alliances color alliescolor = colRGB(255,255,0); //list of blobs encompassing all objects in universe //LinkedList smBlobList; //BlobProperties smBlobProperties; //fog-of-war sub-blob stuff BlobProperties smFOWBlobProperties; real32 smFOW_AsteroidK1; real32 smFOW_AsteroidK2; real32 smFOW_AsteroidK3; real32 smFOW_AsteroidK4; real32 smFOW_DustGasK2; real32 smFOW_DustGasK3; real32 smFOW_DustGasK4; real32 smFOWBlobUpdateTime = SM_FOWBlobUpdateTime; //global flag which says the sensors manager is active bool32 smSensorsActive = FALSE; bool32 smSensorsDisable = FALSE; //for updating blobs sdword smRenderCount; color smBackgroundColor = colFuscia, smIntBackgroundColor; color smBlobColor = SM_BlobColor; color smBlobColorHigh = SM_BlobColorHigh; color smBlobColorLow = SM_BlobColorLow; color smIntBlobColor; color smIntBlobColorHigh; color smIntBlobColorLow; //for zooming real32 smZoomTime; region **smScrollListLeft, **smScrollListTop, **smScrollListRight, **smScrollListBottom; sdword smScrollCountLeft, smScrollCountTop, smScrollCountRight, smScrollCountBottom; sdword smScrollDistLeft, smScrollDistTop, smScrollDistRight, smScrollDistBottom; sdword smScrollLeft, smScrollTop, smScrollRight, smScrollBottom; vector smLookStart, smLookEnd; vector smEyeStart, smEyeEnd; bool8 smZoomingIn = FALSE, smZoomingOut = FALSE, smFocus = FALSE, smFocusTransition = FALSE; FocusCommand *smFocusCommand = NULL; //for selections rectangle smSelectionRect; //blob *smLastClosestBlob = NULL; blob *closestBlob = NULL; blob *probeBlob = NULL; //for enabling 'ghost mode' after a player dies bool32 smGhostMode = FALSE; bool32 ioSaveState; //option for fuzzy sensors blobs sdword smFuzzyBlobs = TRUE; smblurry smBlurryArray[SM_BlurryArraySize]; sdword smBlurryIndex = 0; //cursor text font, from mouse.c extern fonthandle mouseCursorFont; color smCurrentWorldPlaneColor; real32 smCurrentCameraDistance; //switch for 'instant' transitions to sensors manager bool32 smInstantTransition = FALSE; real32 smCurrentZoomLength; real32 smCurrentMainViewZoomLength; //for horizon tick marks smticktext smTickText[SM_MaxTicksOnScreen]; sdword smTickTextIndex; //for panning the world plane about whilley-nilley vector smCameraLookatPoint = {0.0f, 0.0f, 0.0f}; vector smCameraLookVelocity = {0.0f, 0.0f, 0.0f}; bool32 smCentreWorldPlane = FALSE; //info for sorting the blobs blob **smBlobSortList = NULL; sdword smBlobSortListLength = 0; sdword smNumberBlobsSorted = 0; //for multiplayer hyperspace sdword MP_HyperSpaceFlag=FALSE; //for sensors weirdness #define NUM_WEIRD_POINTS 600 #define MAX_REPLACEMENTS 5 #define WEIRDUNIVERSESTRETCH 5/4 typedef struct { vector location; color color; real32 fade; bool32 ping; } weirdStruct; static weirdStruct smWeird[NUM_WEIRD_POINTS]; udword smSensorWeirdness=0; //region for hyperspace button regionhandle smHyperspaceRegion = NULL; //what ships have a TO in the SM ubyte smShipTypeRenderFlags[TOTAL_NUM_SHIPS] = { SM_TO, //AdvanceSupportFrigate 0, //AttackBomber SM_TO | SM_Mesh, //Carrier 0, //CloakedFighter SM_TO, //CloakGenerator SM_TO, //DDDFrigate 0, //DefenseFighter SM_TO, //DFGFrigate SM_TO, //GravWellGenerator 0, //HeavyCorvette SM_TO | SM_Mesh, //HeavyCruiser 0, //HeavyDefender 0, //HeavyInterceptor SM_TO, //IonCannonFrigate 0, //LightCorvette 0, //LightDefender 0, //LightInterceptor 0, //MinelayerCorvette SM_TO, //MissileDestroyer SM_Mesh | SM_Exclude, //Mothership 0, //MultiGunCorvette SM_Exclude, //Probe SM_Exclude, //ProximitySensor 0, //RepairCorvette SM_TO, //ResearchShip SM_TO, //ResourceCollector SM_TO, //ResourceController 0, //SalCapCorvette SM_TO, //SensorArray SM_TO, //StandardDestroyer SM_TO, //StandardFrigate SM_Exclude, //Drone SM_Exclude, //TargetDrone SM_Mesh, //HeadShotAsteroid SM_Mesh | SM_Exclude, //CryoTray 0, //P1Fighter SM_TO, //P1IonArrayFrigate 0, //P1MissileCorvette SM_TO | SM_Mesh, //P1Mothership 0, //P1StandardCorvette 0, //P2AdvanceSwarmer SM_TO, //P2FuelPod SM_TO | SM_Mesh, //P2Mothership SM_TO, //P2MultiBeamFrigate 0, //P2Swarmer SM_TO, //P3Destroyer SM_TO, //P3Frigate SM_TO | SM_Mesh, //P3Megaship SM_TO | SM_Mesh, //FloatingCity SM_TO, //CargoBarge SM_TO | SM_Mesh, //MiningBase SM_TO | SM_Mesh, //ResearchStation 0, //JunkYardDawg SM_TO, //JunkYardHQ 0, //Ghostship 0, //Junk_LGun 0, //Junk_SGun 0, //ResearchStationBridge 0 //ResearchStationTower }; ubyte smDerelictTypeMesh[NUM_DERELICTTYPES] = { 0, //AngelMoon, 0, //AngelMoon_clean, 0, //Crate, SM_Mesh, //FragmentPanel0a, SM_Mesh, //FragmentPanel0b, SM_Mesh, //FragmentPanel0c, SM_Mesh, //FragmentPanel1, SM_Mesh, //FragmentPanel2, SM_Mesh, //FragmentPanel3, SM_Mesh, //FragmentStrut, 0, //Homeworld, 0, //LifeBoat, 0, //PlanetOfOrigin, 0, //PlanetOfOrigin_scarred, 0, //PrisonShipOld, 0, //PrisonShipNew, SM_Mesh, //Scaffold, SM_Mesh, //Scaffold_scarred, SM_Mesh, //ScaffoldFingerA_scarred, SM_Mesh, //ScaffoldFingerB_scarred, 0, //Shipwreck, //pre-revision ships as junkyard derelicts: 0, //JunkAdvanceSupportFrigate, SM_Mesh, //JunkCarrier, 0, //JunkDDDFrigate, 0, //JunkHeavyCorvette, SM_Mesh, //JunkHeavyCruiser, 0, //JunkIonCannonFrigate, 0, //JunkLightCorvette, 0, //JunkMinelayerCorvette, 0, //JunkMultiGunCorvette, 0, //JunkRepairCorvette, 0, //JunkResourceController, 0, //JunkSalCapCorvette, 0, //JunkStandardFrigate, 0, //Junk0_antenna 0, //Junk0_fin1 0, //Junk0_fin2 0, //Junk0_GunAmmo 0, //Junk0_panel 0, //Junk0_sensors 0, //Junk1_partA 0, //Junk1_partB 0, //Junk1_shell 0, //Junk1_strut 0, //Junk2_panelA 0, //Junk2_panelB 0, //Junk2_panelC 0, //Junk2_panelD 0, //Junk2_shipwreck 0, //Junk3_Boiler 0, //Junk3_BoilerCasing 0, //M13PanelA 0, //M13PanelB 0, //M13PanelC //hyperspace gate dummy derelict 0, //HyperspaceGate }; GLboolean smBigPoints; /*----------------------------------------------------------------------------- tweakables for the sensors manager from sensors.script -----------------------------------------------------------------------------*/ //for blobs sdword smBlobUpdateRate = SM_BlobUpdateRate; real32 smClosestMargin = SM_ClosestMargin; real32 smFarthestMargin = SM_FarthestMargin; //for selections real32 smSelectedFlashSpeed = SM_SelectedFlashSpeed; real32 smFocusScalar = SM_FocusScalar; real32 smFocusRadius = SM_FocusRadius; sdword smSelectionWidth = SM_SelectionWidth; sdword smSelectionHeight = SM_SelectionHeight; //zooming in/out real32 smZoomLength = SM_ZoomLength; real32 smMainViewZoomLength = SM_MainViewZoomLength; //for tactical overlay color smPlayerListTextColor = SM_PlayerListTextColor; color smCursorTextColor = SM_CursorTextColor; color smTOColor = SM_TOColor; sdword smPlayerListTextMargin = SM_PlayerListTextMargin; sdword smPlayerListMarginX = SM_PlayerListMarginX; sdword smPlayerListMarginY = SM_PlayerListMarginY; sdword smTOBottomCornerX = SM_TOBottomCornerX; sdword smTOBottomCornerY = SM_TOBottomCornerY; sdword smTOLineSpacing = SM_TOLineSpacing; real32 smTORadius = 1.0f; //for world plane color smWorldPlaneColor = SM_WorldPlaneColor; color smMovePlaneColor = SM_MovePlaneColor; color smHeightCircleColor = SM_HeightCircleColor; real32 smWorldPlaneDistanceFactor = SM_WorldPlaneDistanceFactor; sdword smWorldPlaneSegments = SM_WorldPlaneSegments; real32 smMovementWorldPlaneDim = SM_MovementWorldPlaneDim; real32 smRadialTickStart = SM_RadialTickStart; real32 smRadialTickInc = SM_RadialTickInc; real32 smTickInnerMult = SM_TickInnerMult; real32 smTickOuterMult = SM_TickOuterMult; real32 smTickExtentFactor = SM_TickExtentFactor; real32 smBlobCircleSize = SM_BlobCircleSize; real32 smShortFootLength = SM_ShortFootLength; real32 smBackgroundDim = SM_BackgroundDim; //for horizon ticks real32 smHorizTickAngle = SM_HorizTickAngle; real32 smHorizTickVerticalFactor = SM_HorizTickVerticalFactor; real32 smHorizonLineDistanceFactor = SM_HorizonLineDistanceFactor; real32 smHorizonTickHorizFactor = SM_HorizonTickHorizFactor; sdword smTickTextSpacing = SM_TickTextSpacing; //for movement/selections real32 smTickLength = SM_TickLength; real32 smClosestDistance = SM_ClosestDistance; //for rendering real32 smProjectionScale = SM_ProjectionScale; //for hot key groups sdword smHotKeyOffsetX = 0; sdword smHotKeyOffsetY = 0; //for panning the world plane about whilley-nilley real32 smPanSpeedMultiplier = SM_PanSpeedMultiplier; real32 smPanTrack = SM_PanTrack; real32 smPanEvalThreshold = SM_PanEvalThreshold; real32 smPanUnivExtentMult = SM_PanUnivExtentMult; sdword smCursorPanX = SM_CursorPanX; sdword smCursorPanY = SM_CursorPanY; sdword smMaxFrameTicks = SM_MaxFrameTicks; /*----------------------------------------------------------------------------- tweakables for sensors manager from level files -----------------------------------------------------------------------------*/ //depth cuing real32 smDepthCueRadius = SM_DepthCueRadius; real32 smDepthCueStartRadius = SM_DepthCueStartRadius; real32 smCircleBorder = SM_CircleBorder; real32 smZoomMax = SM_ZoomMax; real32 smZoomMin = SM_ZoomMin; real32 smZoomMinFactor = SM_ZoomMinFactor; real32 smZoomMaxFactor = SM_ZoomMaxFactor; real32 smInitialDistance = SM_InitialDistance; real32 smUniverseSizeX = SM_UniverseSizeX; real32 smUniverseSizeY = SM_UniverseSizeY; real32 smUniverseSizeZ = SM_UniverseSizeZ; /*----------------------------------------------------------------------------- Tweakables for the fleet intel version of the SM -----------------------------------------------------------------------------*/ real32 smSkipFadeoutTime = SM_SkipFadeoutTime; /*----------------------------------------------------------------------------- Tweak table for sensors.script -----------------------------------------------------------------------------*/ scriptEntry smTweaks[] = { //sensors manager tweaks makeEntry(smBlobUpdateRate , scriptSetSdwordCB), makeEntry(smSelectedFlashSpeed , scriptSetReal32CB), makeEntry(smFocusScalar , scriptSetReal32CB), makeEntry(smFocusRadius , scriptSetReal32CB), makeEntry(smZoomLength , scriptSetReal32CB), makeEntry(smMainViewZoomLength , scriptSetReal32CB), makeEntry(smPlayerListTextColor , scriptSetRGBCB), makeEntry(smCursorTextColor , scriptSetRGBCB), makeEntry(smTOColor , scriptSetRGBCB), makeEntry(smWorldPlaneColor , scriptSetRGBCB), makeEntry(smPlayerListTextMargin, scriptSetSdwordCB), makeEntry(smPlayerListMarginX , scriptSetSdwordCB), makeEntry(smPlayerListMarginY , scriptSetSdwordCB), makeEntry(smTOBottomCornerX , scriptSetSdwordCB), makeEntry(smTOBottomCornerY , scriptSetSdwordCB), makeEntry(smTOLineSpacing , scriptSetSdwordCB), makeEntry(smTickLength , scriptSetReal32CB), makeEntry(smClosestDistance , scriptSetReal32CB), makeEntry(smProjectionScale , scriptSetReal32CB), makeEntry(smSelectionWidth , scriptSetSdwordCB), makeEntry(smSelectionHeight , scriptSetSdwordCB), makeEntry(smZoomMaxFactor , scriptSetReal32CB), makeEntry(smZoomMinFactor , scriptSetReal32CB), makeEntry(smHotKeyOffsetX , scriptSetSdwordCB), makeEntry(smHotKeyOffsetY , scriptSetSdwordCB), makeEntry(smClosestMargin , scriptSetReal32CB), makeEntry(smFarthestMargin , scriptSetReal32CB), makeEntry(smBlobCircleSize , scriptSetReal32CB), makeEntry(smShortFootLength , scriptSetReal32CB), makeEntry(smBlobColor , scriptSetRGBCB), makeEntry(smBlobColorHigh , scriptSetRGBCB), makeEntry(smBlobColorLow , scriptSetRGBCB), makeEntry(smTORadius , scriptSetReal32CB), makeEntry(smPanSpeedMultiplier , scriptSetReal32CB), makeEntry(smPanTrack , scriptSetReal32CB), makeEntry(smPanEvalThreshold , scriptSetReal32CB), makeEntry(smCursorPanX , scriptSetSdwordCB), makeEntry(smCursorPanY , scriptSetSdwordCB), makeEntry(smMaxFrameTicks , scriptSetSdwordCB), makeEntry(smSkipFadeoutTime , scriptSetReal32CB), makeEntry(smWorldPlaneDistanceFactor, scriptSetReal32CB), makeEntry(smPanUnivExtentMult , scriptSetReal32CB), // { "smBobDensityLow", scriptSetReal32CB, &smBlobProperties.bobDensityLow }, // { "smBobDensityHigh", scriptSetReal32CB, &smBlobProperties.bobDensityHigh }, // { "smBobStartSphereSize", scriptSetReal32CB, &smBlobProperties.bobStartSphereSize }, // { "smBobRadiusCombineMargin", scriptSetReal32CB, &smBlobProperties.bobRadiusCombineMargin }, // { "smBobOverlapFactor", scriptSetReal32CB, &smBlobProperties.bobOverlapFactor }, // { "smBobSmallestRadius", scriptSetReal32CB, &smBlobProperties.bobSmallestRadius }, // { "smBobBiggestRadius", scriptSetReal32CB, &smBlobProperties.bobBiggestRadius }, // { "smBobDoingCollisionBobs", scriptSetBool, &smBlobProperties.bobDoingCollisionBobs }, { "FOWBobDensityLow", scriptSetReal32CB, &smFOWBlobProperties.bobDensityLow }, { "FOWBobDensityHigh", scriptSetReal32CB, &smFOWBlobProperties.bobDensityHigh }, { "FOWBobStartSphereSize", scriptSetReal32CB, &smFOWBlobProperties.bobStartSphereSize }, { "FOWBobRadiusCombineMargin", scriptSetReal32CB, &smFOWBlobProperties.bobRadiusCombineMargin }, { "FOWBobOverlapFactor", scriptSetBlobPropertyOverlap, &smFOWBlobProperties }, { "FOWBobSmallestRadius", scriptSetReal32CB, &smFOWBlobProperties.bobSmallestRadius }, { "FOWBobBiggestRadius", scriptSetBlobBiggestRadius, &smFOWBlobProperties }, // { "FOWBobDoingCollisionBobs", scriptSetBool, &smFOWBlobProperties.bobDoingCollisionBobs }, { "FOW_AsteroidK1", scriptSetReal32CB, &smFOW_AsteroidK1 }, { "FOW_AsteroidK2", scriptSetReal32CB, &smFOW_AsteroidK2 }, { "FOW_AsteroidK3", scriptSetReal32CB, &smFOW_AsteroidK3 }, { "FOW_AsteroidK4", scriptSetReal32CB, &smFOW_AsteroidK4 }, { "FOW_DustGasK2", scriptSetReal32CB, &smFOW_DustGasK2 }, { "FOW_DustGasK3", scriptSetReal32CB, &smFOW_DustGasK3 }, { "FOW_DustGasK4", scriptSetReal32CB, &smFOW_DustGasK4 }, { "smFOWBlobUpdateTime", scriptSetReal32CB, &smFOWBlobUpdateTime }, END_SCRIPT_ENTRY }; /*============================================================================= Private Functions: =============================================================================*/ /*----------------------------------------------------------------------------- Name : smStrchr Description : Like strchr but returns NULL when searching for a NULL terminator. Inputs : Outputs : Return : NULL ----------------------------------------------------------------------------*/ void *smStrchr(char *string, char character) { while (*string) { if (character == *string) { return(string); } string++; } return(NULL); } #define SM_NumberTickMarkSpacings 4 #define SM_TickSwitchHysteresis 0.9f #define SM_SpokeLengthFactor 1.05f typedef struct { real32 radius; //'on' radius of the ticks real32 spacing; //spacing between ticks, meters real32 length; //factor of the circle radius } ticklod; real32 smTickSwitchHysteresis = SM_TickSwitchHysteresis; real32 smSpokeLengthFactor = SM_SpokeLengthFactor; ticklod smTickMarkInfo[SM_NumberTickMarkSpacings] = { {100000.0f, 20000.0f, 0.025f}, {50000.0f, 10000.0f, 0.015f}, {10000.0f, 2000.0f, 0.007f}, }; /*----------------------------------------------------------------------------- Name : smWorldPlaneDraw Description : Draw the sensors manager world plane. Inputs : z - height to draw it at so we can use same drawing code for the movement pie plate. c - color to use for drawing the beast bDrawSpokes - true if we are to draw spokes Outputs : Return : ----------------------------------------------------------------------------*/ static real32 smTickFactorX[4] = {0.0f, 1.0f, 0.0f, -1.0f}; static real32 smTickFactorY[4] = {1.0f, 0.0f, -1.0f, 0.0f}; void smWorldPlaneDraw(vector *centre, bool32 bDrawSpokes, color c) { real32 radius = smCamera.distance * smWorldPlaneDistanceFactor; real32 tickExtent = radius * smTickExtentFactor; real32 ringRadius; real32 angle, sinTheta, cosTheta; sdword spoke, LOD, thisLOD; vector spokeRim, tickEnd0, tickEnd1, p0, p1; real32 tickFactorX = 0.0f, tickFactorY = 1.0f, tickRadius; //draw the circle rndTextureEnable(FALSE); ringRadius = (smZoomMin + smZoomMax) / 2.0f * smWorldPlaneDistanceFactor; primCircleOutlineZ(centre, ringRadius, smWorldPlaneSegments, c); //draw the radial ticks tickEnd0.z = tickEnd1.z = centre->z; for (angle = smRadialTickStart; angle < 2.0f * PI; angle += smRadialTickInc) { sinTheta = (real32)sin((double)angle); cosTheta = (real32)cos((double)angle); tickEnd0.x = tickEnd1.x = ringRadius * sinTheta; tickEnd0.y = tickEnd1.y = ringRadius * cosTheta; tickEnd0.x *= smTickInnerMult; tickEnd0.y *= smTickInnerMult; tickEnd1.x *= smTickOuterMult; tickEnd1.y *= smTickOuterMult; vecAdd(p0, *centre, tickEnd0); vecAdd(p1, *centre, tickEnd1); primLine3(&p0, &p1, c); } //draw the spokes with gradations, if applicable if (bDrawSpokes) { spokeRim.z = centre->z; for (LOD = 0; LOD < SM_NumberTickMarkSpacings; LOD++) { if (smTickMarkInfo[LOD].radius <= radius) { break; } } for (spoke = 0; spoke < 4; spoke++) { tickFactorX = smTickFactorX[spoke]; tickFactorY = smTickFactorY[spoke]; spokeRim.y = spokeRim.x = ringRadius * smSpokeLengthFactor; spokeRim.x *= tickFactorX; spokeRim.y *= tickFactorY; vecAdd(p0, *centre, spokeRim); primLine3(centre, &p0, c); for (thisLOD = 0; thisLOD < LOD; thisLOD++) { tickRadius = smTickMarkInfo[thisLOD].spacing; while (tickRadius <= tickExtent) { tickEnd0.x = radius * smTickMarkInfo[thisLOD].length * tickFactorX; tickEnd0.y = radius * smTickMarkInfo[thisLOD].length * tickFactorY; tickEnd1.x = -tickEnd0.x; tickEnd1.y = -tickEnd0.y; tickEnd0.x += tickRadius * tickFactorY; tickEnd0.y += tickRadius * tickFactorX; tickEnd1.x += tickRadius * tickFactorY; tickEnd1.y += tickRadius * tickFactorX; vecAdd(p0, *centre, tickEnd0); vecAdd(p1, *centre, tickEnd1); primLine3(&p0, &p1, c); tickRadius += smTickMarkInfo[thisLOD].spacing; } } } } } /*----------------------------------------------------------------------------- Name : makeShipsNotBeDisabled Description : removes disabled ships from selection Outputs : Return : void ----------------------------------------------------------------------------*/ void makeShipsNotBeDisabled(SelectCommand *selection) { sdword i; for(i=0;i<selection->numShips;i++) { if(selection->ShipPtr[0]->flags & SOF_Disabled) { selection->numShips--; selection->ShipPtr[i] = selection->ShipPtr[selection->numShips]; i--; } } } /*----------------------------------------------------------------------------- Name : smHorizonLineDraw Description : Draw the horizon line with compass tick marks Inputs : cam - context we're rendering from thisBlob - blob we're rendering modelView, projection - current matrices distance - the distance to draw the ring at Outputs : Return : void ----------------------------------------------------------------------------*/ #define cam ((Camera *)voidCam) void smHorizonLineDraw(void *voidCam, hmatrix *modelView, hmatrix *projection, real32 distance) { real32 startAngle, endAngle; real32 x, y, radius; vector startPoint, horizPoint, endPoint; real32 angle, degAngle; bool32 isEnabled = FALSE; sdword nPrintfed; fonthandle oldFont = fontCurrentGet(); // distance = smCurrentCameraDistance; //!!! distance *= smWorldPlaneDistanceFactor; startAngle = cam->angle - PI - DEG_TO_RAD(cam->fieldofview) / 2.0f - smHorizTickAngle * 2.0; endAngle = cam->angle - PI + DEG_TO_RAD(cam->fieldofview) / 2.0f + smHorizTickAngle * 2.0; angle = (real32)floor((double)(startAngle / smHorizTickAngle)) * smHorizTickAngle; startPoint.x = cam->lookatpoint.x + (real32)cos((double)angle) * distance; //position of starting point startPoint.y = cam->lookatpoint.y + (real32)sin((double)angle) * distance; endPoint.z = startPoint.z = cam->lookatpoint.z; fontMakeCurrent(mouseCursorFont); if (glIsEnabled(GL_DEPTH_TEST)) { isEnabled = TRUE; glDisable(GL_DEPTH_TEST); } for (smTickTextIndex = 0; angle < endAngle; angle += smHorizTickAngle) { endPoint.x = cam->lookatpoint.x + (real32)cos((double)(angle + smHorizTickAngle)) * distance;//position of current point endPoint.y = cam->lookatpoint.y + (real32)sin((double)(angle + smHorizTickAngle)) * distance; primLine3(&startPoint, &endPoint, smCurrentWorldPlaneColor);//draw the vertical tick horizPoint.x = endPoint.x; horizPoint.y = endPoint.y; if (cam->eyeposition.z > cam->lookatpoint.z) { horizPoint.z = cam->lookatpoint.z + cam->clipPlaneFar * smHorizTickVerticalFactor; } else { horizPoint.z = cam->lookatpoint.z - cam->clipPlaneFar * smHorizTickVerticalFactor; } //figure out where to draw the tick text selCircleComputeGeneral(modelView, projection, &horizPoint, 1.0f, &x, &y, &radius); dbgAssertOrIgnore(smTickTextIndex < SM_MaxTicksOnScreen); smTickText[smTickTextIndex].x = primGLToScreenX(x); smTickText[smTickTextIndex].y = primGLToScreenY(y); degAngle = -RAD_TO_DEG(angle - smHorizTickAngle); if (degAngle < 0.0f) { degAngle += 360.0f; } if (degAngle > 360.0f) { degAngle -= 360.0f; } if (degAngle < 10) { nPrintfed = sprintf(smTickText[smTickTextIndex].text, "00%.0f", degAngle); } else if (degAngle < 100) { nPrintfed = sprintf(smTickText[smTickTextIndex].text, "0%.0f", degAngle); } else { nPrintfed = sprintf(smTickText[smTickTextIndex].text, "%.0f", degAngle); } dbgAssertOrIgnore(nPrintfed < SM_TickTextChars); if (cam->eyeposition.z > cam->lookatpoint.z) { smTickText[smTickTextIndex].y -= fontHeight(" ") + smTickTextSpacing; } else { smTickText[smTickTextIndex].y += smTickTextSpacing; } smTickText[smTickTextIndex].x -= fontWidth(smTickText[smTickTextIndex].text) / 2; smTickTextIndex++; //draw the horizontal tick primLine3(&endPoint, &horizPoint, smCurrentWorldPlaneColor); horizPoint.x = (endPoint.x - cam->lookatpoint.x) * smHorizonTickHorizFactor + cam->lookatpoint.x; horizPoint.y = (endPoint.y - cam->lookatpoint.y) * smHorizonTickHorizFactor + cam->lookatpoint.y; horizPoint.z = cam->lookatpoint.z; primLine3(&endPoint, &horizPoint, smCurrentWorldPlaneColor); startPoint = endPoint; //draw from this point to next point next time through } if (isEnabled) { glEnable(GL_DEPTH_TEST); } fontMakeCurrent(oldFont); } #undef cam /*----------------------------------------------------------------------------- Name : smTickTextDraw Description : Draw the tick text created in smHorizonLineDraw Inputs : Outputs : Return : void Note : must be in 2d mode for this function ----------------------------------------------------------------------------*/ void smTickTextDraw(void) { fonthandle oldFont = fontCurrentGet(); fontMakeCurrent(mouseCursorFont); for (smTickTextIndex--; smTickTextIndex >= 0; smTickTextIndex--) { fontPrint(smTickText[smTickTextIndex].x, smTickText[smTickTextIndex].y, smCurrentWorldPlaneColor, smTickText[smTickTextIndex].text); } fontMakeCurrent(oldFont); } /*----------------------------------------------------------------------------- Name : smBlobDrawClear Description : Render all the ships inside a blob. This would be for blobs with player ships or when player has full sensors researched. Inputs : camera - POV to render from thisBlob - blob we're rendering modelView, projection - current matrices background - color of the blob being drawn to Outputs : Return : void ----------------------------------------------------------------------------*/ //render utility functions //bool8 rndShipVisible(SpaceObj* spaceobj, Camera* camera); //string of ship types to be rendered as meshes void smBlobDrawClear(Camera *camera, blob *thisBlob, hmatrix *modelView, hmatrix *projection, color background) { sdword index, i; SpaceObj **objPtr, *obj; color c = colBlack; lod *level; hmatrix coordMatrixForGL; ShipStaticInfo *shipStaticInfo; bool32 bFlashOn; SpaceObjSelection *blobObjects = thisBlob->blobObjects; real32 radius; hvector objectPos, cameraSpace, screenSpace; smblurry *blurry; sdword nShipTOs = 0; struct { real32 x, y; real32 radius; color c; ShipClass shipClass; } shipTO[SM_NumberTOs]; sdword nBigDots = 0; struct { real32 x, y; color c; } bigDot[SM_NumberBigDots]; real32 pointSize = 0.0; rectangle rect; //flash the selected ships if (fmod((double)universe.totaltimeelapsed, (double)smSelectedFlashSpeed) > smSelectedFlashSpeed / 2.0) { bFlashOn = TRUE; } else { bFlashOn = FALSE; } //draw all objects in the sphere for (index = 0, objPtr = blobObjects->SpaceObjPtr; index < blobObjects->numSpaceObjs; index++, objPtr++) { obj = *objPtr; //#ifdef DEBUG_COLLBLOBS if (obj->flags & SOF_Targetable) //#endif { selCircleCompute(modelView, projection, (SpaceObjRotImpTarg *)obj);//compute selection circle } switch (obj->objtype) { case OBJ_ShipType: if (smNonResources == FALSE) { break; } if (bitTest(((Ship *)obj)->flags, SOF_Hide)) { //don't show hidden ships break; } if (smTacticalOverlay) { if (((Ship *)obj)->playerowner == universe.curPlayerPtr && bitTest(smShipTypeRenderFlags[((Ship *)obj)->shiptype], SM_TO)) { if (nShipTOs < SM_NumberTOs) { shipTO[nShipTOs].x = ((Ship *)obj)->collInfo.selCircleX; shipTO[nShipTOs].y = ((Ship *)obj)->collInfo.selCircleY; shipTO[nShipTOs].radius = ((Ship *)obj)->collInfo.selCircleRadius; shipTO[nShipTOs].c = colRGB(colRed(c)/TO_IconColorFade, colGreen(c)/TO_IconColorFade, colBlue(c)/TO_IconColorFade); shipTO[nShipTOs].shipClass = ((Ship *)obj)->staticinfo->shipclass; nShipTOs++; } } if(((Ship *)obj)->playerowner == universe.curPlayerPtr) { if(((Ship *)obj)->shiptype == GravWellGenerator) { if (((GravWellGeneratorSpec *)((Ship *)obj)->ShipSpecifics)->GravFieldOn) { toFieldSphereDraw(((Ship *)obj),((GravWellGeneratorStatics *) ((ShipStaticInfo *)(((Ship *)obj)->staticinfo))->custstatinfo)->GravWellRadius, 1.0f, TW_GRAVWELL_SPHERE_COLOUR); } } } } if (bitTest(smShipTypeRenderFlags[((Ship *)obj)->shiptype], SM_Mesh)) { //if it's a ship type to render as a mesh level = lodLevelGet((void *)obj, &camera->eyeposition, &obj->posinfo.position); if ((level->flags & LM_LODType) == LT_Mesh) { if (!(bFlashOn && (((Ship *)obj)->flags & SOF_Selected))) { if(!bitTest(obj->flags,SOF_Cloaked) || ((Ship *)obj)->playerowner == universe.curPlayerPtr) { //if ship isn't cloaked, draw, or if ship is players, draw glPushMatrix(); shipStaticInfo = (ShipStaticInfo *)obj->staticinfo; hmatMakeHMatFromMat(&coordMatrixForGL,&((SpaceObjRot *)obj)->rotinfo.coordsys); hmatPutVectIntoHMatrixCol4(obj->posinfo.position,coordMatrixForGL); glMultMatrixf((float *)&coordMatrixForGL);//ship's rotation matrix rndLightingEnable(TRUE); shPushLightMatrix(&coordMatrixForGL); i = ((Ship *)obj)->colorScheme; if (rndShipVisible(obj, camera)) { bool32 wireOn; extern bool8 g_WireframeHack; wireOn = g_WireframeHack; g_WireframeHack = FALSE; if (((Ship *)obj)->bindings != NULL) { meshRenderShipHierarchy(((Ship *)obj)->bindings, ((Ship *)obj)->currentLOD, (meshdata *)level->pData, i); } else { meshRender((meshdata *)level->pData, i); } g_WireframeHack = (ubyte)wireOn; } shPopLightMatrix(); glDisable(GL_BLEND); glDisable(GL_ALPHA_TEST); rndLightingEnable(FALSE); rndTextureEnable(FALSE); glPopMatrix(); } } } else { //else no LOD at this level goto justRenderAsDot; } } //else draw it as a pixel else if ( (!bitTest(obj->flags,SOF_Cloaked) || allianceIsShipAlly((Ship *)obj, universe.curPlayerPtr)) && ((obj->attributes & ATTRIBUTES_SMColorField) != ATTRIBUTES_SMColorInvisible) ) { //if ship isn't cloaked, draw, or if ship is players, draw justRenderAsDot: #if TO_STANDARD_COLORS if (((Ship *)obj)->playerowner == universe.curPlayerPtr) { c = teFriendlyColor; } else if (allianceIsShipAlly((Ship *)obj, universe.curPlayerPtr)) { c = teAlliedColor; } else { c = teHostileColor; } if (obj->attributes & ATTRIBUTES_SMColorField) // overide with special colors { if ((obj->attributes & ATTRIBUTES_SMColorField) == ATTRIBUTES_SMColorYellow) { c = teAlliedColor; } else if ((obj->attributes & ATTRIBUTES_SMColorField) == ATTRIBUTES_SMColorGreen) { c = teFriendlyColor; } } #else //SM_STANDARD_COLORS c = teColorSchemes[((Ship *)obj)->colorScheme].tacticalColor; #endif //SM_STANDARD_COLORS if (smTacticalOverlay) { if (((Ship *)obj)->playerowner == universe.curPlayerPtr && bitTest(smShipTypeRenderFlags[((Ship *)obj)->shiptype], SM_TO)) //if (((Ship *)obj)->shiptype == ResourceCollector) { if (nShipTOs < SM_NumberTOs) { shipTO[nShipTOs].x = ((Ship *)obj)->collInfo.selCircleX; shipTO[nShipTOs].y = ((Ship *)obj)->collInfo.selCircleY; shipTO[nShipTOs].radius = ((Ship *)obj)->collInfo.selCircleRadius; shipTO[nShipTOs].c = colRGB(colRed(c)/TO_IconColorFade, colGreen(c)/TO_IconColorFade, colBlue(c)/TO_IconColorFade); shipTO[nShipTOs].shipClass = ((Ship *)obj)->staticinfo->shipclass; nShipTOs++; } } } if (((Ship *)obj)->flags & SOF_Selected) { if (bFlashOn) { c = background; } } // if ((((Ship *)obj)->playerowner->playerIndex == universe.curPlayerIndex)) // { //enable double-size points pointSize = 2.0f; // //glPointSize(2.0f); // } // else // { // pointSize = 1.0f; // //glPointSize(1.0f); // } rndTextureEnable(FALSE); if ((!smBigPoints) && pointSize != 1.0f && ((Ship *)obj)->collInfo.selCircleRadius > 0.0f) { dbgAssertOrIgnore(nBigDots < SM_NumberBigDots); bigDot[nBigDots].x = ((Ship *)obj)->collInfo.selCircleX; bigDot[nBigDots].y = ((Ship *)obj)->collInfo.selCircleY; bigDot[nBigDots].c = c; nBigDots++; } else { glPointSize(pointSize); primPoint3(&obj->posinfo.position, c); //everything is rendered as a point glPointSize(1.0f); } } break; case OBJ_AsteroidType: if (smResources == FALSE) { break; } radius = obj->staticinfo->staticheader.staticCollInfo.collspheresize; if (radius > SM_LargeResourceSize) { pointSize = 2.0f; //glPointSize(2.0f); } rndTextureEnable(FALSE); #if TO_STANDARD_COLORS c = teResourceColor; #else c = obj->staticinfo->staticheader.LOD->pointColor; #endif if ((!smBigPoints) && pointSize != 1.0f && ((Ship *)obj)->collInfo.selCircleRadius > 0.0f) { dbgAssertOrIgnore(nBigDots < SM_NumberBigDots); bigDot[nBigDots].x = ((Ship *)obj)->collInfo.selCircleX; bigDot[nBigDots].y = ((Ship *)obj)->collInfo.selCircleY; bigDot[nBigDots].c = c; nBigDots++; } else { glPointSize(pointSize); primPoint3(&obj->posinfo.position, c); //everything is rendered as a point glPointSize(1.0f); } pointSize = 1.0f; break; case OBJ_NebulaType: case OBJ_GasType: case OBJ_DustType: if (smResources == FALSE) { break; } memcpy(&objectPos, &obj->posinfo.position, sizeof(vector)); objectPos.w = 1.0f; // c = obj->staticinfo->staticheader.LOD->pointColor; // c = colWhite; hmatMultiplyHMatByHVec(&cameraSpace, modelView, &objectPos);//in camera space hmatMultiplyHMatByHVec(&screenSpace, projection, &cameraSpace);//in screen space // primBlurryPoint22(primGLToScreenX(screenSpace.x / screenSpace.w), //everything is rendered as a blurry point // primGLToScreenY(screenSpace.y / screenSpace.w), c); if (screenSpace.z > 0.0f && smBlurryIndex < SM_BlurryArraySize) { #if TO_STANDARD_COLORS smBlurryArray[smBlurryIndex].c = teResourceColor; #else smBlurryArray[smBlurryIndex].c = obj->staticinfo->staticheader.LOD->pointColor; #endif smBlurryArray[smBlurryIndex].x = primGLToScreenX(screenSpace.x / screenSpace.w); smBlurryArray[smBlurryIndex].y = primGLToScreenY(screenSpace.y / screenSpace.w); smBlurryIndex++; } break; case OBJ_DerelictType: if (((Derelict *)obj)->derelicttype == HyperspaceGate) { goto renderDerelictAsDot; } level = lodLevelGet((void *)obj, &camera->eyeposition, &obj->posinfo.position); if (bitTest(smDerelictTypeMesh[((Derelict *)obj)->derelicttype], SM_Mesh) && (level->flags & LM_LODType) == LT_Mesh) { if ( (!bitTest(obj->flags,SOF_Cloaked)) && ((obj->attributes & ATTRIBUTES_SMColorField) != ATTRIBUTES_SMColorInvisible) ) { //if it isn't cloaked, draw glPushMatrix(); shipStaticInfo = (ShipStaticInfo *)obj->staticinfo; hmatMakeHMatFromMat(&coordMatrixForGL,&((SpaceObjRot *)obj)->rotinfo.coordsys); hmatPutVectIntoHMatrixCol4(obj->posinfo.position,coordMatrixForGL); glMultMatrixf((float *)&coordMatrixForGL);//ship's rotation matrix rndLightingEnable(TRUE); shPushLightMatrix(&coordMatrixForGL); i = ((Derelict *)obj)->colorScheme; if (rndShipVisible(obj, camera)) { bool32 wireOn; extern bool8 g_WireframeHack; wireOn = g_WireframeHack; g_WireframeHack = FALSE; meshRender((meshdata *)level->pData, i); g_WireframeHack = (ubyte)wireOn; } shPopLightMatrix(); glDisable(GL_BLEND); glDisable(GL_ALPHA_TEST); rndLightingEnable(FALSE); rndTextureEnable(FALSE); glPopMatrix(); } } else { renderDerelictAsDot: #if TO_STANDARD_COLORS c = teNeutralColor; #else c = obj->staticinfo->staticheader.LOD->pointColor; #endif if (singlePlayerGame && (((Derelict *)obj)->derelicttype == PrisonShipOld)) { c = teFriendlyColor; } rndTextureEnable(FALSE); primPoint3(&obj->posinfo.position,c); //everything is rendered as a point } break; default: break; } } //display the nebulae tendrils as strings rndTextureEnable(FALSE); rndLightingEnable(FALSE); glEnable(GL_BLEND); rndAdditiveBlends(FALSE); glShadeModel(GL_FLAT); for (index = 0; index < numNebulae; index++) { sdword t; nebulae_t* neb = &nebNebulae[index]; glBegin(GL_LINES); for (t = 0; t < neb->numTendrils; t++) { color c = neb->tendrilTable[t].colour; glColor4ub(colRed(c), colGreen(c), colBlue(c), 192); glVertex3fv((GLfloat*)&neb->tendrilTable[t].a->position); glColor4ub(colRed(c), colGreen(c), colBlue(c), 192); glVertex3fv((GLfloat*)&neb->tendrilTable[t].b->position); } glEnd(); } glDisable(GL_BLEND); if (smBlurryIndex > 0 || nShipTOs > 0 || nBigDots > 0) { toicon *icon; color col; real32 radius; primModeSet2(); for (blurry = smBlurryArray; smBlurryIndex > 0; smBlurryIndex--, blurry++) { primBlurryPoint22(blurry->x, blurry->y, blurry->c); } for (index = 0; index < nShipTOs; index++) { icon = toClassIcon[shipTO[index].shipClass]; toClassUsed[shipTO[index].shipClass][0] = TRUE; if (shipTO[index].radius > 0.0f) { radius = max(shipTO[index].radius, smTORadius); col = shipTO[index].c; primLineLoopStart2(1, col); for (i = icon->nPoints - 1; i >= 0; i--) { primLineLoopPoint3F(shipTO[index].x + icon->loc[i].x * radius, shipTO[index].y + icon->loc[i].y * radius); } } primLineLoopEnd2(); } for (index = 0; index < nBigDots; index++) { rect.x0 = primGLToScreenX(bigDot[index].x); rect.y0 = primGLToScreenY(bigDot[index].y); rect.x1 = rect.x0 + 2; rect.y1 = rect.y0 + 2; primRectSolid2(&rect, bigDot[index].c); } primModeClear2(); rndLightingEnable(FALSE); rndTextureEnable(FALSE); } } /*----------------------------------------------------------------------------- Name : SensorsWeirdnessUtilities Description : Utility functions for the sensors weirdness in the single player game Inputs : various Outputs : various Return : various ----------------------------------------------------------------------------*/ //generates a random location within (and slightly outside) the bounds of the universe vector smwGenerateRandomPoint(void) { vector vec; vec.x = (real32)frandyrandombetween(RANDOM_AI_PLAYER,-smUniverseSizeX*WEIRDUNIVERSESTRETCH,smUniverseSizeX*WEIRDUNIVERSESTRETCH); vec.y = (real32)frandyrandombetween(RANDOM_AI_PLAYER,-smUniverseSizeY*WEIRDUNIVERSESTRETCH,smUniverseSizeY*WEIRDUNIVERSESTRETCH); vec.z = (real32)frandyrandombetween(RANDOM_AI_PLAYER,-smUniverseSizeZ*WEIRDUNIVERSESTRETCH,smUniverseSizeZ*WEIRDUNIVERSESTRETCH); return vec; } //generates a random color for the point color smwGenerateRandomColor(void) { udword colornum; color col; colornum = (udword)randyrandom(RANDOM_AI_PLAYER, 7); switch (colornum) { case 0: // col = teFriendlyColor; // break; case 1: case 2: case 3: col = teHostileColor; break; case 4: case 5: case 6: default: col = teResourceColor; break; } return col; } void smwGeneratePing(vector location) { sdword pingcnt; char name[20] = "0"; //very small chance of a new ping if (((udword)randyrandom(RANDOM_AI_PLAYER, 200)) <= 1) { pingcnt = randyrandom(RANDOM_AI_PLAYER, 3); sprintf(name, "Weirdness%i", pingcnt); pingAnomalyPingRemove(name); pingAnomalyPositionPingAdd(name, &location); } } /*----------------------------------------------------------------------------- Name : smSensorWeirdnessDraw Description : Draws the sensor manager malfunction in Missions 7 and 8 Inputs : Outputs : Draws a bunch of weirdness on the screen Return : void ----------------------------------------------------------------------------*/ void smSensorWeirdnessDraw(hmatrix *modelView, hmatrix *projection) { udword i,j, num_replaces; static udword num_points; static udword redraw = 0; vector tempvec; rectangle rect; if (!redraw) { num_points = (udword)randyrandom(RANDOM_AI_PLAYER, (smSensorWeirdness/3)); num_points += (2*smSensorWeirdness/3); redraw = randyrandombetween(RANDOM_AI_PLAYER, 20, 30); } else { redraw--; } num_replaces = (udword)randyrandom(RANDOM_AI_PLAYER, MAX_REPLACEMENTS); for (i=0;i<num_replaces;i++) { //chose a random point j = (udword)randyrandom(RANDOM_AI_PLAYER, smSensorWeirdness); //generate a random location for it smWeird[j].location = smwGenerateRandomPoint(); smWeird[j].color = smwGenerateRandomColor(); smWeird[j].fade = 0.0f; smwGeneratePing(smWeird[j].location); } primModeSet2(); for (i=0;i<num_points;i++) { // Reimplement the weirdness transSingleTotalTransform(&tempvec, modelView, projection, &smWeird[i].location); rect.x0 = primGLToScreenX(tempvec.x); rect.y0 = primGLToScreenY(tempvec.y); rect.x1 = rect.x0 + 2; rect.y1 = rect.y0 + 2; primRectSolid2(&rect, smWeird[i].color); } primModeClear2(); } /*----------------------------------------------------------------------------- Name : smSensorsWeirdnessInit Description : Initializes the sensors weirdness stuff Inputs : Outputs : Fills the smWeirdCol and smWeirdLoc arrays Return : void ----------------------------------------------------------------------------*/ void smSensorWeirdnessInit(void) { udword i; for (i=0;i<NUM_WEIRD_POINTS;i++) { smWeird[i].location = smwGenerateRandomPoint(); smWeird[i].color = smwGenerateRandomColor(); smWeird[i].ping = FALSE; } } /*----------------------------------------------------------------------------- Name : smEnemyFogOfWarBlobCallback Description : Sub-blob creation callback for creating fog-of-war sub-blobs Inputs : superBlob - the blob we're looking in obj - object to evaluate for inclusion Outputs : Return : TRUE if it's an enemy ship or a foggy resource ----------------------------------------------------------------------------*/ bool32 smEnemyFogOfWarBlobCallback(blob *superBlob, SpaceObj *obj) { switch (obj->objtype) { case OBJ_ShipType: //make sure it's an enemy ship if (allianceIsShipAlly((Ship *)obj,universe.curPlayerPtr)) { //if this is an allied ship (alliance formed while in SM) return(FALSE); } if (((Ship *)obj)->flags & (SOF_Hide | SOF_Cloaked)) { //don't show hidden or cloaked ships return(FALSE); } if ((obj->attributes & ATTRIBUTES_SMColorField) == ATTRIBUTES_SMColorInvisible) { return(FALSE); } return(TRUE); case OBJ_BulletType: break; case OBJ_AsteroidType: return(TRUE); case OBJ_NebulaType: break; case OBJ_GasType: case OBJ_DustType: return(TRUE); case OBJ_DerelictType: case OBJ_EffectType: case OBJ_MissileType: break; } return(FALSE); } /*----------------------------------------------------------------------------- Name : smBlobDrawCloudy Description : Draw a cloudy sensors blob, such as one in the shroud. Inputs : same as for the clear draw Outputs : Return : void ----------------------------------------------------------------------------*/ #define SM_VISUALIZE_SUBBLOBS 0 void smBlobDrawCloudy(Camera *camera, blob *thisBlob, hmatrix *modelView, hmatrix *projection, color background) { sdword index; SpaceObj **objPtr, *obj; color c = colBlack; hvector objectPos, cameraSpace, screenSpace; SpaceObjSelection *blobObjects = thisBlob->blobObjects; Node *subBlobNode; blob *subBlob; sdword nShips; smblurry *blurry; sdword nBigDots = 0; struct { real32 x, y; color c; } bigDot[SM_NumberBigDots]; rectangle rect; real32 radius; real32 pointSize; real32 screenX, screenY; glPointSize(2.0f); //compute a list of sub-blobs for the enemies. It will be deleted with the parent blob. if (thisBlob->subBlobs.num == BIT31) { //if list not yet created bobSubBlobListCreate(&smFOWBlobProperties, &thisBlob->subBlobs, thisBlob, smEnemyFogOfWarBlobCallback); thisBlob->subBlobTime = universe.totaltimeelapsed; } else { if (universe.totaltimeelapsed - thisBlob->subBlobTime >= smFOWBlobUpdateTime) { bobListDelete(&thisBlob->subBlobs); bobSubBlobListCreate(&smFOWBlobProperties, &thisBlob->subBlobs, thisBlob, smEnemyFogOfWarBlobCallback); thisBlob->subBlobTime = universe.totaltimeelapsed; } } //go through all sub-blobs and remove any that are hidden due to too many resources thisBlob->nHiddenShips = 0; for (subBlobNode = thisBlob->subBlobs.head; subBlobNode != NULL; subBlobNode = subBlobNode->next) { subBlob = (blob *)listGetStructOfNode(subBlobNode); if (subBlob->shipMass == 0.0f) { //if no ships in blob continue; //skip it } // if ((k1 * #rocks + k2 * #rockRUs) / (k3 * #ships + k4 * shipMass) > 1.0) nShips = subBlob->nCapitalShips + subBlob->nAttackShips + subBlob->nNonCombat; if ((smFOW_AsteroidK1 * (real32)subBlob->nRocks + smFOW_AsteroidK2 * subBlob->nRockRUs) / (smFOW_AsteroidK3 * (nShips) + smFOW_AsteroidK4 * subBlob->shipMass) > 1.0f) { //if there are too many asteroids to see these ships #if SM_VISUALIZE_SUBBLOBS primCircleOutlineZ(&subBlob->centre, subBlob->radius, 16, colRGB(0, 255, 0)); #endif thisBlob->nHiddenShips += nShips; continue; //don't draw them } // if (k2 * #dustRUs / (k3 * #ships + k4 * shipMass) > 1.0) if ((smFOW_DustGasK2 * subBlob->nDustRUs) / (smFOW_DustGasK3 * nShips + smFOW_DustGasK4 * subBlob->shipMass) > 1.0f) { //if there's too much dust #if SM_VISUALIZE_SUBBLOBS // selCircleComputeGeneral(modelView, projection, &subBlob->centre, subBlob->radius, &subBlob->screenX, &subBlob->screenY, &subBlob->screenRadius); primCircleOutlineZ(&subBlob->centre, subBlob->radius, 16, colRGB(255, 255, 0)); #endif thisBlob->nHiddenShips += nShips; continue; //don't draw the ships } //there's not too many resources, draw them as normal #if SM_VISUALIZE_SUBBLOBS primCircleOutlineZ(&subBlob->centre, subBlob->radius, 16, colWhite); #endif c = teHostileColor; dbgAssertOrIgnore(nBigDots < SM_NumberBigDots); // bigDot[nBigDots].x = ((Ship *)obj)->collInfo->selCircleX; // bigDot[nBigDots].y = ((Ship *)obj)->collInfo->selCircleY; selCircleComputeGeneral(modelView, projection, &subBlob->centre, 1.0f, &screenX, &screenY, &radius); for (index = subBlob->blobObjects->numSpaceObjs - 1; index >= 0 ; index--) { //all ships in sub-blob get selection circle of sub-blob obj = subBlob->blobObjects->SpaceObjPtr[index]; if (obj->objtype == OBJ_ShipType) { ((Ship *)obj)->collInfo.selCircleX = screenX; ((Ship *)obj)->collInfo.selCircleY = screenY; ((Ship *)obj)->collInfo.selCircleRadius = radius; } } if ((!smBigPoints) && radius > 0.0f) { bigDot[nBigDots].c = c; bigDot[nBigDots].x = screenX; bigDot[nBigDots].y = screenY; nBigDots++; } else { primPoint3(&subBlob->centre, c); } } glPointSize(1.0f); //draw all objects in the sphere for (index = 0, objPtr = blobObjects->SpaceObjPtr; index < blobObjects->numSpaceObjs; index++, objPtr++) { obj = *objPtr; //#ifdef DEBUG_COLLBLOBS if (obj->flags & SOF_Targetable) //#endif { selCircleCompute(modelView, projection, (SpaceObjRotImpTarg *)obj);//compute selection circle } switch (obj->objtype) { case OBJ_ShipType: if (((obj->flags & (SOF_Cloaked | SOF_Hide))) || //if hidden or cloaked ((obj->attributes & ATTRIBUTES_SMColorField) == ATTRIBUTES_SMColorInvisible)) { thisBlob->nHiddenShips++; } continue; //ships were drawn from sub-blobs case OBJ_NebulaType: continue; //don't even draw nebulae case OBJ_GasType: case OBJ_DustType: if (smResources == FALSE) { goto dontRenderThisResource; } memcpy(&objectPos, &obj->posinfo.position, sizeof(vector)); objectPos.w = 1.0f; hmatMultiplyHMatByHVec(&cameraSpace, modelView, &objectPos);//in camera space hmatMultiplyHMatByHVec(&screenSpace, projection, &cameraSpace);//in screen space if (screenSpace.z > 0.0f && smBlurryIndex < SM_BlurryArraySize) { #if TO_STANDARD_COLORS smBlurryArray[smBlurryIndex].c = teResourceColor; #else smBlurryArray[smBlurryIndex].c = obj->staticinfo->staticheader.LOD->pointColor; #endif smBlurryArray[smBlurryIndex].x = primGLToScreenX(screenSpace.x / screenSpace.w); smBlurryArray[smBlurryIndex].y = primGLToScreenY(screenSpace.y / screenSpace.w); smBlurryIndex++; } break; case OBJ_AsteroidType: #if TO_STANDARD_COLORS c = teResourceColor; #else c = obj->staticinfo->staticheader.LOD->pointColor; #endif radius = obj->staticinfo->staticheader.staticCollInfo.collspheresize; if (radius > SM_LargeResourceSize) { pointSize = 2.0f; } else { pointSize = 1.0f; } if ((!smBigPoints) && pointSize != 1.0f && ((Ship *)obj)->collInfo.selCircleRadius > 0.0f) { dbgAssertOrIgnore(nBigDots < SM_NumberBigDots); bigDot[nBigDots].x = ((Ship *)obj)->collInfo.selCircleX; bigDot[nBigDots].y = ((Ship *)obj)->collInfo.selCircleY; bigDot[nBigDots].c = c; nBigDots++; } else { glPointSize(pointSize); primPoint3(&obj->posinfo.position, c); glPointSize(1.0f); } break; case OBJ_DerelictType: if (((Derelict *)obj)->derelicttype == Crate) { //crates are draw as grey dots c = teCrateColor; } else if ((((Derelict *)obj)->derelicttype == PrisonShipOld) && spGetCurrentMission() == MISSION_8_THE_CATHEDRAL_OF_KADESH) { //!!! Single Player game mission specific Code //In Mission 8, the PrisonShipOld derelict shows up //as a friendly ship dbgAssertOrIgnore(nBigDots < SM_NumberBigDots); bigDot[nBigDots].x = ((Derelict *)obj)->collInfo.selCircleX; bigDot[nBigDots].y = ((Derelict *)obj)->collInfo.selCircleY; bigDot[nBigDots].c = teFriendlyColor; nBigDots++; } else { #if TO_STANDARD_COLORS c = teNeutralColor; #else c = obj->staticinfo->staticheader.LOD->pointColor; #endif } primPoint3(&obj->posinfo.position, c); break; default: //#ifndef DEBUG_COLLBLOBS // dbgAssertOrIgnore(FALSE); // don't assert if DEBUG_COLLBLOBS because debug collblobs can have bullets,etc. //#endif break; } dontRenderThisResource:; } if (smBlurryIndex > 0 || nBigDots > 0) { primModeSet2(); for (blurry = smBlurryArray; smBlurryIndex > 0; smBlurryIndex--, blurry++) { primBlurryPoint22(blurry->x, blurry->y, blurry->c); } for (index = 0; index < nBigDots; index++) { rect.x0 = primGLToScreenX(bigDot[index].x); rect.y0 = primGLToScreenY(bigDot[index].y); rect.x1 = rect.x0 + 2; rect.y1 = rect.y0 + 2; primRectSolid2(&rect, bigDot[index].c); } primModeClear2(); } rndLightingEnable(FALSE); rndTextureEnable(FALSE); } /*----------------------------------------------------------------------------- Name : smBlobListSort Description : qsort callback for sorting a list of blob pointers by sortDistance Inputs : Outputs : Return : ----------------------------------------------------------------------------*/ int smBlobListSort(const void *p0, const void *p1) { blob *b0 = *((blob **)p0); blob *b1 = *((blob **)p1); if (b0->cameraSortDistance < b1->cameraSortDistance) { return(-1); } else { return(1); } } /*----------------------------------------------------------------------------- Name : smBlobsSortToCamera Description : list - linked list of blobs camera - camera to sort to Inputs : Outputs : (Re)allocates and fills in smBlobSortList with pointers to the blobs in list, sorted by distance from camera->eyeposition Return : ----------------------------------------------------------------------------*/ void smBlobsSortToCamera(LinkedList *list, Camera *camera) { blob *thisBlob; Node *node; vector distance; //grow the blob sorting list if needed if (list->num > smBlobSortListLength) { smBlobSortListLength = list->num; smBlobSortList = memRealloc(smBlobSortList, sizeof(blob **) * smBlobSortListLength, "smBlobSortList", NonVolatile); } node = list->head; //do a pass through the blobs to figure their sorting distances and count the blobs for (node = list->head, smNumberBlobsSorted = 0; node != NULL; node = node->next, smNumberBlobsSorted++) { thisBlob = (blob *)listGetStructOfNode(node); vecSub(distance, camera->eyeposition, thisBlob->centre); thisBlob->cameraSortDistance = vecMagnitudeSquared(distance);//figure out a distance for sorting smBlobSortList[smNumberBlobsSorted] = thisBlob; //store reference to blob } dbgAssertOrIgnore(smNumberBlobsSorted == list->num); qsort(smBlobSortList, smNumberBlobsSorted, sizeof(blob **), smBlobListSort); } /*----------------------------------------------------------------------------- Name : smBlobDropDistance Description : Compute the distance from the movement cursor to a drop-down line for a blob when the move mechanism is up. Inputs : thisBlob - blob to use for the drop-down line Outputs : Return : distance from center of blob's plane point to the centre point of the movement plane point. ----------------------------------------------------------------------------*/ real32 smBlobDropLineDistance(blob *thisBlob) { vector planePoint = thisBlob->centre; planePoint.z = selCentrePoint.z; return(ABS(piePlanePoint.x - planePoint.x) + //manhattan distance ABS(piePlanePoint.y - planePoint.y)); } /*----------------------------------------------------------------------------- Name : smBlobsDraw Description : Draws all blobs for the current sensors screen Inputs : list - linked list of objects Outputs : Return : Pointer to blob most directly under the mouse cursor or NULL if none. ----------------------------------------------------------------------------*/ blob *smBlobsDraw(Camera *camera, LinkedList *list, hmatrix *modelView, hmatrix *projection, sdword sensorLevel) { oval o; blob *thisBlob; // Node *node; blob *closestMoveBlob = NULL; real32 closestMoveDistance = REALlyBig, moveDistance; sdword index, blobIndex, nSegments, distance, closestDistance = SDWORD_Max; real32 distanceToOrigin, distanceToOriginSquared, factor; real32 closestSortDistance = REALlyBig, farthestSortDistance = REALlyNegative, highestBlob = 0.0f; color c; sdword radius; vector p0, p1; real32 x, y, screenRadius; #if BOB_VERBOSE_LEVEL >= 2 sdword nBlobs = 0; #endif bool32 bClosestMove = FALSE; // used for playing the tick sound when a blob is highligted static bool32 bPlayedSound; // ditto sdword carrierHalfWidth = 0, mothershipHalfWidth = 0; char *carrier = NULL, *mothership = NULL; fonthandle oldFont = 0; mouseCursorObjPtr = NULL; //Falko: got an obscure crash where mouseCursorObjPtr was mangled, will this work? smBigPoints = TRUE; memset(toClassUsed, 0, sizeof(toClassUsed)); closestBlob = NULL; distanceToOriginSquared = vecMagnitudeSquared(camera->eyeposition); distanceToOrigin = fmathSqrt(distanceToOriginSquared); smBlobsSortToCamera(list, camera); primModeSet2(); //go through the list to find the farthest and closest blobs, plus the blob closest //to movement cursor // node = list->head; // while (node != NULL) // thisBlob = (blob *)listGetStructOfNode(node); // node = node->next; for (blobIndex = 0; blobIndex < smNumberBlobsSorted; blobIndex++) { thisBlob = smBlobSortList[blobIndex]; closestSortDistance = min(closestSortDistance, thisBlob->cameraSortDistance); farthestSortDistance = max(farthestSortDistance, thisBlob->cameraSortDistance); highestBlob = max(highestBlob, ABS(thisBlob->centre.z)); moveDistance = smBlobDropLineDistance(thisBlob); if (moveDistance < closestMoveDistance) { //closest blob to movement mechanism closestMoveDistance = moveDistance; closestMoveBlob = thisBlob; } } closestSortDistance = fmathSqrt(closestSortDistance); farthestSortDistance = fmathSqrt(farthestSortDistance); if (closestSortDistance >= farthestSortDistance) { closestSortDistance = farthestSortDistance - 1.0f; } closestSortDistance -= smClosestMargin; farthestSortDistance += smFarthestMargin; //do 1 pass (backwards) through all the blobs to render the blobs themselves for (blobIndex = smNumberBlobsSorted - 1; blobIndex >= 0; blobIndex--) { thisBlob = smBlobSortList[blobIndex]; //compute on-screen location of the blob //!!! tune this circle a bit better selCircleComputeGeneral(modelView, projection, &thisBlob->centre, thisBlob->radius, &thisBlob->screenX, &thisBlob->screenY, &thisBlob->screenRadius); if (thisBlob->screenRadius <= 0.0f) { continue; } o.centreX = primGLToScreenX(thisBlob->screenX); o.centreY = primGLToScreenY(thisBlob->screenY); o.radiusX = o.radiusY = primGLToScreenScaleX(thisBlob->screenRadius); if ((thisBlob->flags & (BTF_Explored | BTF_ProbeDroid)) || //if player has ships in this blob (sensorLevel == 2 && bitTest(thisBlob->flags, BTF_UncloakedEnemies)))//or you have a sensors array and there are uncloaked enemies { //v-grad the blob color if (thisBlob->centre.z > 0.0f) { //if blob is above world plane factor = thisBlob->centre.z / highestBlob; c = colBlend(smIntBlobColorHigh, smIntBlobColor, factor); } else { //blob below the world plane factor = (-thisBlob->centre.z) / highestBlob; c = colBlend(smIntBlobColorLow, smIntBlobColor, factor); } //depth-grad the blob brightness factor = fmathSqrt(thisBlob->cameraSortDistance); factor = (factor - closestSortDistance) / (farthestSortDistance - closestSortDistance); if (factor < 0.0f) { factor = 0.0f; } if (factor > 1.0f) { factor = 1.0f; } c = colBlend(smIntBackgroundColor, c, factor); thisBlob->lastColor = c; //radius = o.radiusX * smCircleBorder / 65536; if (thisBlob->screenRadius <= SM_BlobRadiusMax) { radius = primGLToScreenScaleX(thisBlob->screenRadius * smCircleBorder); /* nSegments = radius * SEL_SegmentsMax / MAIN_WindowHeight + SEL_SegmentsMin; nSegments = min(nSegments, SEL_SegmentsMax); */ nSegments = pieCircleSegmentsCompute(thisBlob->screenRadius * smCircleBorder); if (smFuzzyBlobs) { primCircleBorder(o.centreX, o.centreY, o.radiusX, radius, nSegments, c); } else { primCircleSolid2(o.centreX, o.centreY, radius, nSegments, c); } } } #if BOB_VERBOSE_LEVEL >= 2 nBlobs++; #endif if (mouseInRectGeneral(o.centreX - o.radiusX, o.centreY - o.radiusY, o.centreX + o.radiusX, o.centreY + o.radiusY)) { //if inside bounding box of circle distance = ABS(o.centreX - mouseCursorX()) + ABS(o.centreY - mouseCursorY()); if (distance < closestDistance) { //if closest yet closestDistance = distance; closestBlob = thisBlob; } } } #if SM_VERBOSE_LEVEL >= 3 fontPrintf(20, MAIN_WindowHeight / 2, colWhite, "%d Blobs", nBlobs); #endif //set the selected bit on all selected ships. This is only a temporary flag. for (index = 0; index < selSelected.numShips; index++) { bitSet(selSelected.ShipPtr[index]->flags, SOF_Selected); } lightPositionSet(); primModeClear2(); rndLightingEnable(FALSE); rndTextureEnable(FALSE); //draw the world plane //!!! always where the camera is pointing !!! if (smCentreWorldPlane) { p0.x = p0.y = 0.0f; } else { p0 = smCamera.lookatpoint; } p0.z = 0.0f; smWorldPlaneDraw(&p0, TRUE, smCurrentWorldPlaneColor); //draw the horizon plane smHorizonLineDraw(&smCamera, modelView, projection, smCurrentCameraDistance); primModeSet2(); smTickTextDraw(); primModeClear2(); rndLightingEnable(FALSE); rndTextureEnable(FALSE); //another pass through all the blobs to render the objects in the blobs // node = list->head; // while (node != NULL) // { // thisBlob = (blob *)listGetStructOfNode(node); // node = node->next; if (smTacticalOverlay) { oldFont = fontMakeCurrent(selGroupFont3); carrier = ShipTypeToNiceStr(Carrier); mothership = ShipTypeToNiceStr(Mothership); carrierHalfWidth = fontWidth(carrier) / 2; mothershipHalfWidth = fontWidth(mothership) / 2; } for (blobIndex = 0; blobIndex < smNumberBlobsSorted; blobIndex++) { thisBlob = smBlobSortList[blobIndex]; if ((thisBlob->flags & (BTF_Explored | BTF_ProbeDroid)) || //if players in this blob (sensorLevel == 2 && bitTest(thisBlob->flags, BTF_UncloakedEnemies)))//or you have a sensors array and there are uncloaked enemies { smBlobDrawClear(camera, thisBlob, modelView, projection, thisBlob->lastColor); if (thisBlob->screenRadius > 0.0f) { if (smTacticalOverlay) { if (bitTest(thisBlob->flags, BTF_Mothership)) { primModeSet2(); fontPrint(primGLToScreenX(thisBlob->screenX) - mothershipHalfWidth, primGLToScreenY(thisBlob->screenY) + primGLToScreenScaleX(thisBlob->screenRadius), smTOColor, mothership); primModeClear2(); rndLightingEnable(FALSE); //mouse is self-illuminated rndTextureEnable(FALSE); } else if (bitTest(thisBlob->flags, BTF_Carrier)) { primModeSet2(); fontPrint(primGLToScreenX(thisBlob->screenX) - carrierHalfWidth, primGLToScreenY(thisBlob->screenY) + primGLToScreenScaleX(thisBlob->screenRadius), smTOColor, carrier); primModeClear2(); rndLightingEnable(FALSE); //mouse is self-illuminated rndTextureEnable(FALSE); } } } } else { smBlobDrawCloudy(camera, thisBlob, modelView, projection, thisBlob->lastColor); } } if (smTacticalOverlay) { fontMakeCurrent(oldFont); } //single player Sensor Manager malfunction //threshold is 10 to avoid divide by zero problems if (smSensorWeirdness > 10) { smSensorWeirdnessDraw(modelView, projection); } rndTextureEnable(FALSE); rndLightingEnable(FALSE); { Node *node; Asteroid *thisAsteroid; rndGLStateLog("Minor asteroids"); for (node = universe.MinorSpaceObjList.head; node != NULL; node = node->next) { thisAsteroid = (Asteroid *)listGetStructOfNode(node); dbgAssertOrIgnore(thisAsteroid->objtype == OBJ_AsteroidType && thisAsteroid->asteroidtype == Asteroid0); #if TO_STANDARD_COLORS c = teResourceColor; #else c = thisAsteroid->staticinfo->staticheader.LOD->pointColor; #endif primPoint3(&thisAsteroid->posinfo.position, c); } } //do a pass through the blobs to draw the drop-down lines and blob circles if (piePointSpecMode != PSM_Idle) { //if we're in movement mode // node = list->head; // while (node != NULL) // { // thisBlob = (blob *)listGetStructOfNode(node); // node = node->next; for (blobIndex = 0; blobIndex < smNumberBlobsSorted; blobIndex++) { thisBlob = smBlobSortList[blobIndex]; //draw the blob cirle on the world plane p0 = thisBlob->centre; //position of the yellow circle c = colBlack; if ( (!(thisBlob->flags & (BTF_Explored | BTF_ProbeDroid))) && (sensorLevel != 2)) { //if it's all enemies if (thisBlob->nCapitalShips + thisBlob->nAttackShips + thisBlob->nNonCombat > thisBlob->nHiddenShips) { //and there are visible ships here if (closestMoveBlob == thisBlob && closestMoveDistance < closestMoveBlob->radius / SM_BlobClosenessFactor) { c = TW_SHIP_LINE_CLOSEST_COLOR; //draw in closest move color bClosestMove = TRUE; } else { c = TW_MOVE_ENEMY_COLOR; //in enemy move color } } } else if (thisBlob->nCapitalShips + thisBlob->nAttackShips + thisBlob->nNonCombat + thisBlob->nFriendlyShips > 0) { //else player has ships here if (thisBlob->nFriendlyShips == 0) { c = TW_MOVE_ENEMY_COLOR; //in enemy move color } else if (closestMoveBlob == thisBlob && closestMoveDistance < closestMoveBlob->radius / SM_BlobClosenessFactor) { c = TW_SHIP_LINE_CLOSEST_COLOR; //draw in closest move color bClosestMove = TRUE; } else { c = TW_MOVE_PIZZA_COLOR; //in move color } } if (c != colBlack) { //if a color was specified, whatever it may have been p1.x = thisBlob->centre.x; //draw from blob to move plane p1.y = thisBlob->centre.y; p1.z = piePlanePoint.z; if (ABS(p1.z - p0.z) >= smShortFootLength) { primLine3(&p0, &p1, c); //draw line to plane selCircleComputeGeneral(modelView, projection, &p1, smBlobCircleSize, &x, &y, &screenRadius); nSegments = pieCircleSegmentsCompute(screenRadius); primCircleOutlineZ(&p1, smBlobCircleSize, nSegments, c);//draw the circle on plane } } } } //now remove the selected bit from all selected ships. for (index = 0; index < selSelected.numShips; index++) { bitClear(selSelected.ShipPtr[index]->flags, SOF_Selected); } if (bClosestMove && !bPlayedSound) { bPlayedSound = TRUE; soundEvent(NULL, UI_MoveChimes); } else if (!bClosestMove) { bPlayedSound = FALSE; } primModeSet2(); pingListDraw(&smCamera, modelView, projection, &smViewRectangle); primModeClear2(); return(closestBlob); } /*----------------------------------------------------------------------------- Name : smBlobRenderSelected Description : Renders the specifed blob as though it was selected, using a colored outline. Inputs : b - blob to render c - color of outline to draw Outputs : Return : ----------------------------------------------------------------------------*/ /* void smBlobRenderSelected(blob *b, color c) { oval o; sdword index; SpaceObj **obj; SpaceObjSelection *blobObjects = b->blobObjects; primModeSet2(); o.centreX = primGLToScreenX(b->screenX); o.centreY = primGLToScreenY(b->screenY); o.radiusX = o.radiusY = primGLToScreenScaleX(b->screenRadius); primOvalArcOutline2(&o, 0.0f, TWOPI, 1, 16, c); primModeClear2(); rndTextureEnable(FALSE); rndLightingEnable(FALSE); for (index = 0, obj = blobObjects->SpaceObjPtr; index < blobObjects->numSpaceObjs; index++, obj++) { rndTextureEnable(FALSE); primPoint3(&(*obj)->posinfo.position, c); //everything is rendered as a point // (*obj)->staticinfo->staticheader.staticCollInfo.collspheresize, } } */ /*----------------------------------------------------------------------------- Name : smXXXFactorGet Description : Gets the current zoom factors based on the current zoom time. Inputs : current - current point in function, in frames range - extent of function, in frames Outputs : Return : current zoom factor Notes : currently a linear interpolation. ----------------------------------------------------------------------------*/ real32 smScrollFactorGet(real32 current, real32 range) { real32 val; val = current / range; if (val < 0.0f) { val = 0.0f; } if (val > 1.0f) { val = 1.0f; } return(val); } /* real32 smEyeFactorGet(real32 current, real32 range) { return(current / range); } real32 smLookFactorGet(real32 current, real32 range) { return(current / range); } */ /*----------------------------------------------------------------------------- Name : smZoomUpdate Description : Updates the zoom function while transitioning TO sensors manager. Inputs : current - current point in function, in time range - extent of function, in time bUpdateCamera - update camera if true Outputs : Return : void ----------------------------------------------------------------------------*/ void smZoomUpdate(real32 current, real32 range, bool32 bUpdateCamera) { real32 scrollFactor; real32 eyeFactor; real32 lookFactor; sdword index, delta, val; vector distvec; scrollFactor = smScrollFactorGet(current, range); eyeFactor = lookFactor = scrollFactor; // eyeFactor = smEyeFactorGet(current, range); // lookFactor = smLookFactorGet(current, range); //animate the sides of the sensors manager screen val = (sdword)((real32)smScrollDistLeft * scrollFactor); delta = val - smScrollLeft; smScrollLeft = val; smViewRectangle.x0 += delta; for (index = 0; index < smScrollCountLeft; index++) { regRegionScroll(smScrollListLeft[index], delta, 0); } val = (sdword)((real32)smScrollDistTop * scrollFactor); delta = val - smScrollTop; smScrollTop = val; smViewRectangle.y0 += delta; for (index = 0; index < smScrollCountTop; index++) { regRegionScroll(smScrollListTop[index], 0, delta); } val = (sdword)((real32)smScrollDistRight * scrollFactor); delta = val - smScrollRight; smScrollRight = val; smViewRectangle.x1 -= delta; for (index = 0; index < smScrollCountRight; index++) { regRegionScroll(smScrollListRight[index], -delta, 0); } val = (sdword)((real32)smScrollDistBottom * scrollFactor); delta = val - smScrollBottom; smScrollBottom = val; smViewRectangle.y1 -= delta; for (index = 0; index < smScrollCountBottom; index++) { regRegionScroll(smScrollListBottom[index], 0, -delta); } smIntBackgroundColor = colMultiplyClamped(smBackgroundColor, scrollFactor); smIntBlobColor = colMultiplyClamped(smBlobColor, scrollFactor); smIntBlobColorHigh = colMultiplyClamped(smBlobColorHigh, scrollFactor); smIntBlobColorLow = colMultiplyClamped(smBlobColorLow, scrollFactor); rndSetClearColor(colRGBA(colRed(smIntBackgroundColor), colGreen(smIntBackgroundColor), colBlue(smIntBackgroundColor), 255)); btgSetColourMultiplier((1.0f - smBackgroundDim) * (1.0f - scrollFactor) + smBackgroundDim); if (piePointSpecMode != PSM_Idle) { smCurrentWorldPlaneColor = smWorldPlaneColor; } else { smCurrentWorldPlaneColor = colMultiplyClamped(smWorldPlaneColor, scrollFactor); } //blend between the far clip distances of the 2 cameras smCurrentCameraDistance = (smCamera.clipPlaneFar - mrCamera->clipPlaneFar) * scrollFactor + mrCamera->clipPlaneFar; //animate the camera position based upon the current zoom factors if (bUpdateCamera) { vecVectorsBlend(&smCamera.lookatpoint, &smLookStart, &smLookEnd, lookFactor); vecVectorsBlend(&smCamera.eyeposition, &smEyeStart, &smEyeEnd, eyeFactor); vecSub(distvec, smCamera.eyeposition, smCamera.lookatpoint); // distvec.z *= -1.0f; GetDistanceAngleDeclination(&smCamera, &distvec); } //mouseClipToRect(NULL); } /*----------------------------------------------------------------------------- Name : smSensorsCloseForGood Description : Closes sensors manager after zooming in. Inputs : Outputs : Return : ----------------------------------------------------------------------------*/ void smSensorsCloseForGood(void) { #if SM_VERBOSE_LEVEL >= 1 dbgMessage("smSensorsCloseForGood"); #endif if (tutorial) { tutGameMessage("Game_SensorsClose"); } mrRenderMainScreen = TRUE; feScreenDelete(smBaseRegion); // bobListDelete(&smBlobList); // glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); rndSetClearColor(colRGBA(colRed(universe.backgroundColor), colGreen(universe.backgroundColor), colBlue(universe.backgroundColor), 255)); smSensorsActive = FALSE; universe.dontUpdateRenderList = FALSE; if (smScrollListLeft) memFree(smScrollListLeft); if (smScrollListRight) memFree(smScrollListRight); if (smScrollListTop) memFree(smScrollListTop); if (smScrollListBottom) memFree(smScrollListBottom); universe.mainCameraCommand.actualcamera.ignoreZoom = FALSE; mouseCursorShow(); mrHoldLeft = mrHoldRight = mrNULL; if (ioSaveState) { ioEnable(); } if(smFocusOnMothershipOnClose) { // CameraStackEntry *entry; // entry = currentCameraStackEntry(&universe.mainCameraCommand); ccFocusOnMyMothership(&universe.mainCameraCommand); smFocusOnMothershipOnClose = FALSE; // if(entry != currentCameraStackEntry(&universe.mainCameraCommand)) // listDeleteNode(&entry->stacklink); } smZoomingIn = FALSE; smZoomingOut = FALSE; mouseClipToRect(NULL); //make sure mouse does not stay locked to the SM viewport region MP_HyperSpaceFlag = FALSE; bitClear(tbDisable,TBDISABLE_SENSORS_USE); btgSetColourMultiplier(1.0f); //make sure we always come out of the SM with the BTG in good order } void smBlobSphereDraw(blob *closestBlob) { udword angle = 0; vector origin = {0.0, 0.0, 0.0}; hmatrix rotmat; while(angle < 180) { hmatMakeRotAboutZ(&rotmat,cos(DEG_TO_RAD(angle)),sin(DEG_TO_RAD(angle))); hmatPutVectIntoHMatrixCol4(closestBlob->centre, rotmat); glPushMatrix(); glMultMatrixf((GLfloat *)&rotmat); primCircleOutline3(&origin, closestBlob->radius, 8, 0, colWhite, X_AXIS); glPopMatrix(); angle+=40; } angle = 0; while(angle < 180) { hmatMakeRotAboutX(&rotmat,cos(DEG_TO_RAD(angle)),sin(DEG_TO_RAD(angle))); hmatPutVectIntoHMatrixCol4(closestBlob->centre, rotmat); glPushMatrix(); glMultMatrixf((GLfloat *)&rotmat); primCircleOutline3(&origin, closestBlob->radius, 8, 0, colWhite, Z_AXIS); glPopMatrix(); angle+=40; } } /*----------------------------------------------------------------------------- Name : smAllBlobsPiePlateDraw Description : Draws lines from all blobs to the pie plate for the movement mechanism. Inputs : distance -distance from camera to centre of pie plate Outputs : Return : void ----------------------------------------------------------------------------*/ /* void smAllBlobsPiePlateDraw(real32 distance) { Node *node; blob *thisBlob; bool32 dohackloop = TRUE; real32 closestDistance = REALlyBig, length; vector mouse_pos,tempvec; real32 tempreal; blob *closestBlob = NULL; probeBlob = NULL; if(mrNeedProbeHack()) dohackloop = TRUE; else dohackloop = FALSE; node = smBlobList.head; if (piePointSpecZ != 0.0f) { //if a height was specified mouse_pos = pieHeightPoint; } else { mouse_pos = piePlanePoint; //else move to point on plane } while (node) { thisBlob = (blob *)listGetStructOfNode(node); node = node->next; if(!dohackloop) { if (!bitTest(thisBlob->flags, BTF_Explored) && universe.curPlayerPtr->sensorLevel != 2) { continue; } length = smBlobDropLineDraw(thisBlob, TW_SHIP_LINE_COLOR); if (length < closestDistance) { //if this ship closest so far closestDistance = length; closestBlob = thisBlob; } } else { //do closestblob checking first in this loop vecSub(tempvec,mouse_pos,thisBlob->centre); tempreal = fsqrt(vecMagnitudeSquared(tempvec)); if(tempreal < closestDistance) { closestDistance = tempreal; closestBlob = thisBlob; } if (!bitTest(thisBlob->flags, BTF_Explored) && universe.curPlayerPtr->sensorLevel != 2) { continue; } length = smBlobDropLineDraw(thisBlob, TW_SHIP_LINE_COLOR); } } glDisable(GL_DEPTH_TEST); if(!dohackloop) { if (closestBlob != NULL && closestDistance < closestBlob->radius / SM_BlobClosenessFactor) { smBlobDropLineDraw(closestBlob, TW_SHIP_LINE_CLOSEST_COLOR); } } else { if (closestBlob != NULL) { probeBlob = closestBlob; vecSub(tempvec,mouse_pos,probeBlob->centre); tempreal = fsqrt(vecMagnitudeSquared(tempvec)); if(tempreal < probeBlob->radius) { smBlobSphereDraw(closestBlob); } else { probeBlob = NULL; } } } glEnable(GL_DEPTH_TEST); } */ /*----------------------------------------------------------------------------- Name : smMovePlaneDraw Description : Draw the movement plane for the sensors manager. Inputs : distance - distance from camera to selection centre Outputs : Return : ----------------------------------------------------------------------------*/ /* void smMovePlaneDraw(real32 distance) { smWorldPlaneDraw(pieHeightPoint.z, FALSE, smMovePlaneColor); } */ /*----------------------------------------------------------------------------- Name : smBabyRattleDraw Description : Draw the movement lines and cursor for the movement mechanism while in the sensors manager. Inputs : distance - distance from camera to selection centre Outputs : Return : ----------------------------------------------------------------------------*/ /* void smBabyRattleDraw(real32 distance) { ; } */ /*----------------------------------------------------------------------------- Name : smClickedOnPlayer Description : returns the a pointer to the player you right clicked on. NULL otherwise/ Inputs : none Outputs : player clicked on or NULL Return : void ----------------------------------------------------------------------------*/ sdword smClickedOnPlayer(rectangle *viewportRect) { fonthandle oldfont; rectangle playerColorRect; sdword index; oldfont = fontMakeCurrent(selGroupFont2); playerColorRect.y1 = viewportRect->y1 - smPlayerListMarginY; playerColorRect.y0 = playerColorRect.y1 - fontHeight(" "); playerColorRect.x0 = viewportRect->x0 + smPlayerListMarginX; playerColorRect.x1 = playerColorRect.x0 + fontHeight(" "); //draw the list of player names/colors for (index = universe.numPlayers - 1; index >= 0; index--) { if (universe.players[index].playerState==PLAYER_ALIVE) { playerColorRect.x1 = fontWidth(playerNames[index]) + fontHeight(" ")*2; if ((mouseInRect(&playerColorRect)) && (index!=sigsPlayerIndex)) { return (index); } playerColorRect.y0 -= smPlayerListMarginY + fontHeight(" ");//update the position playerColorRect.y1 -= smPlayerListMarginY + fontHeight(" "); } } fontMakeCurrent(oldfont); return (-1); } /*----------------------------------------------------------------------------- Name : smPlayerNamesDraw Description : Draw the names of the players in a multi-player game. Inputs : viewportRect - boundaries of the current viewport Outputs : Return : void ----------------------------------------------------------------------------*/ void smPlayerNamesDraw(rectangle *viewportRect) { fonthandle oldfont; sdword index; rectangle playerColorRect; color c; char buffer[50]; sdword bounty; oldfont = fontMakeCurrent(selGroupFont2); playerColorRect.y1 = viewportRect->y1 - smPlayerListMarginY; playerColorRect.y0 = playerColorRect.y1 - fontHeight(" "); playerColorRect.x0 = viewportRect->x0 + smPlayerListMarginX; playerColorRect.x1 = playerColorRect.x0 + fontHeight(" "); //draw the list of player names/colors for (index = universe.numPlayers - 1; index >= 0; index--) { if (universe.players[index].playerState==PLAYER_ALIVE) { sdword x; bool32 playerhasdroppedOutOrQuit = playerHasDroppedOutOrQuit(index); c = teColorSchemes[index].textureColor.base; if (playerhasdroppedOutOrQuit) { c = HorseRaceDropoutColor; } primRectSolid2(&playerColorRect, c); //draw colored rectangle x = playerColorRect.x1 + smPlayerListTextMargin; fontPrint(x, //print the player name in a stock color playerColorRect.y0, playerhasdroppedOutOrQuit ? HorseRaceDropoutColor : smPlayerListTextColor, playerNames[index]); x += fontWidth(playerNames[index])+fontWidth(" "); if (index != sigsPlayerIndex) { if ((allianceArePlayersAllied(&universe.players[sigsPlayerIndex],&universe.players[index])) || ((universe.players[sigsPlayerIndex].Allies!=0)&&(index == sigsPlayerIndex))) { fontPrint(x, playerColorRect.y0, playerhasdroppedOutOrQuit ? HorseRaceDropoutColor : alliescolor, strGetString(strPlayersAllied)); } } x += fontWidth(strGetString(strPlayersAllied)); if((!singlePlayerGame) && (tpGameCreated.bountySize != MG_BountiesOff)) { //draw bounty values fontPrint(x, playerColorRect.y0, playerhasdroppedOutOrQuit ? HorseRaceDropoutColor : colWhite, "B: "); bounty = getPlayerBountyRender(&universe.players[index]); /*itoa(bounty,buffer,10);*/ sprintf(buffer, "%d", bounty); x += fontWidth("B: "); fontPrint(x, playerColorRect.y0, playerhasdroppedOutOrQuit ? HorseRaceDropoutColor : colWhite, buffer); x += fontWidth(buffer) + fontWidth(" "); } if (playerhasdroppedOutOrQuit) { fontPrint(x,playerColorRect.y0, c, (playersReadyToGo[index] == PLAYER_QUIT) ? strGetString(strQuit) : strGetString(strDroppedOut)); } playerColorRect.y0 -= smPlayerListMarginY + fontHeight(" ");//update the position playerColorRect.y1 -= smPlayerListMarginY + fontHeight(" "); } } fontMakeCurrent(oldfont); } /*----------------------------------------------------------------------------- Name : smCursorTextDraw Description : Draw sensors manager tactical overlay. This includes the player names/colors and a breakdown of what's in a mission sphere. Inputs : viewportRect - boundaries of the current viewport selectedBlob - blob under mouse cursor, or NULL if none. sensorLevel - current sensors level Outputs : Return : void ----------------------------------------------------------------------------*/ void smCursorTextDraw(rectangle *viewportRect, blob *selectedBlob, sdword sensorLevel) { char *cursorText = NULL; SpaceObj *object; fonthandle fhSave; //now draw the cursor text to reflect what is under the mouse cursor if (selectedBlob != NULL) { //if the mouse is over a blob if ((selectedBlob->flags & (BTF_Explored | BTF_ProbeDroid))) { //if this blob has been explored if ((object = selClickFromArray(selectedBlob->blobObjects->SpaceObjPtr, selectedBlob->blobObjects->numSpaceObjs, mouseCursorX(),mouseCursorY())) != NULL) { switch (object->objtype) { case OBJ_ShipType: if (((Ship *)object)->playerowner == universe.curPlayerPtr) { // cursorText = strGetString(strPlayerUnits); cursorText = ShipTypeToNiceStr(((Ship *)object)->shiptype); } else if (allianceIsShipAlly((Ship *)object, universe.curPlayerPtr)) { cursorText = strGetString(strAlliedUnits); } else { cursorText = strGetString(strEnemyUnits); } break; case OBJ_AsteroidType: case OBJ_NebulaType: case OBJ_GasType: case OBJ_DustType: cursorText = strGetString(strResources); break; case OBJ_DerelictType: switch (((Derelict *)object)->derelicttype) { case PrisonShipOld: case PrisonShipNew: case Shipwreck: case JunkAdvanceSupportFrigate: case JunkCarrier: case JunkDDDFrigate: case JunkHeavyCorvette: case JunkHeavyCruiser: case JunkIonCannonFrigate: case JunkLightCorvette: case JunkMinelayerCorvette: case JunkMultiGunCorvette: case JunkRepairCorvette: case JunkResourceController: case JunkSalCapCorvette: case JunkStandardFrigate: cursorText = strGetString(strDerelictShip); break; default: cursorText = NULL; break; } break; default: break; } } } else { //else unexplored blob if (sensorLevel == 0) { //don't know anything on plain blobs cursorText = strGetString(strUnexplored); } else { //else we've got some sensors available if ((object = selClickFromArray(selectedBlob->blobObjects->SpaceObjPtr, selectedBlob->blobObjects->numSpaceObjs, mouseCursorX(),mouseCursorY())) != NULL) { switch (object->objtype) { case OBJ_ShipType: cursorText = strGetString(strEnemyUnits); break; case OBJ_AsteroidType: cursorText = strGetString(strAsteroids); break; case OBJ_NebulaType: cursorText = strGetString(strNebula); break; case OBJ_GasType: cursorText = strGetString(strGasClouds); break; case OBJ_DustType: cursorText = strGetString(strDustClouds); break; case OBJ_DerelictType: cursorText = strGetString(strDerelictShip); break; default: break; } } } } } //cursor text chosen, print the cursor text if applicable if (cursorText != NULL) { fhSave = fontMakeCurrent(mouseCursorFont); fontPrint(viewportRect->x0 + smPlayerListMarginX, viewportRect->y1 - fontHeight(cursorText) - smPlayerListMarginY, TW_CURSORTEXT_COLOR, cursorText); fontMakeCurrent(fhSave); } } /*----------------------------------------------------------------------------- Name : smTacticalOverlayDraw Description : Draw the tactical overlay for sensors manager, including resource types and such Inputs : thisBlob - blob to draw viewportRect - rectangle encompassing the sensors manager sensorLevel - current sensors level Outputs : Return : ----------------------------------------------------------------------------*/ /* void smTacticalOverlayDraw(blob *thisBlob, rectangle *viewportRect, sdword sensorLevel) { sdword x, y, yStart, xSpacing; dbgAssertOrIgnore(thisBlob != NULL); x = mouseCursorX() + smTOBottomCornerX; yStart = y = mouseCursorY() - fontHeight(" ") + smTOBottomCornerY; if (thisBlob->RUs != 0) { //if there's resources in the blob if ((sensorLevel == 2 && bitTest(thisBlob->flags, BTF_Explored)) || bitTest(thisBlob->flags, BTF_ProbeDroid)) { //if max sensor level, print breakdown of resources in the blob xSpacing = fontWidth(strGetString(strResourcesRes))+fontWidth(" "); if (thisBlob->nGasRUs != 0) { fontPrintf(x + xSpacing, y, smTOColor, "%d %s", thisBlob->nGasRUs, strGetString(strGas)); y -= fontHeight(" ") + smTOLineSpacing; } if (thisBlob->nDustRUs != 0) { fontPrintf(x + xSpacing, y, smTOColor, "%d %s", thisBlob->nDustRUs,strGetString(strDust)); y -= fontHeight(" ") + smTOLineSpacing; } if (thisBlob->nRockRUs != 0) { fontPrintf(x + xSpacing, y, smTOColor, "%d %s", thisBlob->nRockRUs, strGetString(strRock)); y -= fontHeight(" ") + smTOLineSpacing; } y += fontHeight(" ") + smTOLineSpacing; fontPrintf(x, y, smTOColor, "%s ",strGetString(strResourcesRes)); y -= fontHeight(" ") + smTOLineSpacing; } else if (sensorLevel >= 1 || bitTest(thisBlob->flags, BTF_Explored)) { //else crappy sensors; just print the types fontPrintf(x, y, smTOColor, "%s %s %s %s", strGetString(strResourcesRes), (thisBlob->flags & (BTF_Asteroid)) ? strGetString(strRock) : "", (thisBlob->flags & (BTF_DustCloud)) ? strGetString(strDust) : "", (thisBlob->flags & (BTF_GasCloud | BTF_Nebula)) ? strGetString(strGas) : ""); y -= fontHeight(" ") + smTOLineSpacing; } } //print types and numbers of ships if (thisBlob->flags & (BTF_Explored | BTF_ProbeDroid)) { if (sensorLevel == 2 || bitTest(thisBlob->flags, BTF_ProbeDroid)) { //level 3 explored if (thisBlob->nNonCombat > 0) { fontPrintf(x, y, smTOColor, "%d %s", thisBlob->nNonCombat, strGetString(strNonCombatShips)); y -= fontHeight(" ") + smTOLineSpacing; } if (thisBlob->nAttackShips > 0) { fontPrintf(x, y, smTOColor, "%d %s", thisBlob->nAttackShips, strGetString(strStrikeCraft)); y -= fontHeight(" ") + smTOLineSpacing; } if (thisBlob->nCapitalShips > 0) { fontPrintf(x, y, smTOColor, "%d %s", thisBlob->nCapitalShips, strGetString(strCapitalShips)); y -= fontHeight(" ") + smTOLineSpacing; } } else if (sensorLevel == 0) { //level 0 explored xSpacing = thisBlob->nCapitalShips + thisBlob->nAttackShips + thisBlob->nNonCombat; if (xSpacing > 0) { fontPrintf(x, y, smTOColor, "%d %s", xSpacing, strGetString(strEnemyUnits)); y -= fontHeight(" ") + smTOLineSpacing; } } else if (sensorLevel == 1) { //level 1 explored xSpacing = thisBlob->nCapitalShips + thisBlob->nAttackShips + thisBlob->nNonCombat; if (xSpacing > 0) { fontPrint(x, y, smTOColor, strGetString(strEnemyUnits)); y -= fontHeight(" ") + smTOLineSpacing; } } } else if (sensorLevel >= 1) { //level 0 unexplored xSpacing = thisBlob->nCapitalShips + thisBlob->nAttackShips + thisBlob->nNonCombat; if (xSpacing > 0) { fontPrint(x, y, smTOColor, strGetString(strEnemyUnits)); y -= fontHeight(" ") + smTOLineSpacing; } } //if nothing was printed, just say it's unexplored if (y == yStart) { fontPrint(x, y, smTOColor, strGetString(strUnexplored)); } } */ /*----------------------------------------------------------------------------- Name : smHotkeyGroupsDraw Description : Draw the location of hotkey groups. Inputs : void Outputs : Return : void ----------------------------------------------------------------------------*/ void smHotkeyGroupsDraw(void) { sdword index; real32 averageSize, x, y, radius; vector centre; fonthandle currentFont = fontCurrentGet(); MaxSelection selection; fontMakeCurrent(selGroupFont3); for (index = 0; index < 10; index++) { MakeShipsNotHidden((SelectCommand *)&selection, (SelectCommand *)&selHotKeyGroup[index]); if (selection.numShips > 0) { centre = selCentrePointComputeGeneral(&selection, &averageSize); selCircleComputeGeneral(&rndCameraMatrix, &rndProjectionMatrix, &centre, 1.0f, &x, &y, &radius); if (radius > 0.0f) { fontPrint(primGLToScreenX(x) + smHotKeyOffsetX, primGLToScreenY(y) + smHotKeyOffsetY, selHotKeyNumberColor, selHotKeyString[index]); } } } fontMakeCurrent(currentFont); } /*----------------------------------------------------------------------------- Name : smPan Description : Special-function button that handles both clicks and pan operations. Inputs : Outputs : Return : ----------------------------------------------------------------------------*/ void smPan(char *name, featom *atom) { if (uicDragX == 0 && uicDragY == 0) { //if it's just a click smCameraLookatPoint.x = smCameraLookatPoint.y = smCameraLookatPoint.z = 0.0f;//recentre the camera } else { //else it's a drag operation vector addVector, lookVector; real32 mult, temp; vecSub(lookVector, smCamera.lookatpoint, smCamera.eyeposition); addVector.x = lookVector.x; addVector.y = lookVector.y; addVector.z = 0.0f; vecNormalize(&addVector); mult = smCamera.distance * smPanSpeedMultiplier; vecScalarMultiply(addVector, addVector, mult); //into/out of screen vector vecScalarMultiply(lookVector, addVector, (real32)uicDragY); vecSubFrom(smCameraLookatPoint, lookVector); //pan into/out of screen temp = addVector.x; //negate-swap x,y addVector.x = addVector.y; addVector.y = -temp; //left/right vector vecScalarMultiply(lookVector, addVector, (real32)uicDragX); vecAddTo(smCameraLookatPoint, lookVector); //pan left/right lookVector.x = lookVector.y = lookVector.z = 0.0f; pieMovePointClipToLimits(smUniverseSizeX * smPanUnivExtentMult, smUniverseSizeY * smPanUnivExtentMult, smUniverseSizeZ, &lookVector, &smCameraLookatPoint); } // smCamera.lookatpoint = smCameraLookatPoint; } /*----------------------------------------------------------------------------- Name : smViewportRender Description : Callback which draws the main sensors manager viewport. Inputs : standard FE callback Outputs : .. Return : void ----------------------------------------------------------------------------*/ void smViewportRender(featom *atom, regionhandle region) { blob *selectedBlob; CameraStackEntry *curentry = currentCameraStackEntry(&universe.mainCameraCommand); sdword frameTicks, sensorLevel; real32 frameStep; vector rememberVec, diffVec; sdword index; frameTicks = utyNFrameTicks; if (frameTicks > smMaxFrameTicks) frameTicks = smMaxFrameTicks; frameStep = (real32)frameTicks / (real32)taskFrequency; cameraControl(&smCamera, FALSE); //update the camera curentry->remembercam.angle = smCamera.angle; curentry->remembercam.declination = smCamera.declination; if (smZoomingOut) { smZoomTime += frameStep; smZoomUpdate(smZoomTime, smCurrentZoomLength, TRUE); if (smZoomTime >= smCurrentZoomLength) { //if done zooming out soundEvent(NULL, UI_SensorsManager); smZoomingOut = FALSE; //stop zooming } if (smZoomTime < smCurrentMainViewZoomLength) { //if still in the regular renderer part of the zoom cameraCopyPositionInfo(&universe.mainCameraCommand.actualcamera, &smCamera); universe.mainCameraCommand.actualcamera.ignoreZoom = TRUE; return; //let mainrgn.c handle the rendering } else { //else we're in the SM rendering part mrRenderMainScreen = FALSE; dbgAssertOrIgnore(smZoomTime >= smCurrentMainViewZoomLength); universe.mainCameraCommand.actualcamera.ignoreZoom = FALSE; } } else if (smZoomingIn) { dbgAssertOrIgnore(smEyeStart.x < (real32)1e19 && smEyeStart.x > (real32)-1e19); smZoomTime -= frameStep; smZoomUpdate(smZoomTime, smCurrentZoomLength, TRUE); if (smZoomTime <= 0.0f) { //fully zoomed in smZoomingIn = FALSE; //...actually close the sensors manager smSensorsCloseForGood(); //stop zooming in already! } if (smZoomTime >= smCurrentMainViewZoomLength) { //if in sm part of zoom cameraCopyPositionInfo(&universe.mainCameraCommand.actualcamera, &smCamera); universe.mainCameraCommand.actualcamera.ignoreZoom = TRUE; } else { //else rendering main game screen if (!smFocusTransition) { //if at transition point smFocusTransition = TRUE; //make sure we only do this once a zoom //... execute the ccfocus thingus if (smFocus) { universe.mainCameraCommand.actualcamera.ignoreZoom = FALSE; ccFocusFar(&universe.mainCameraCommand, smFocusCommand, &universe.mainCameraCommand.actualcamera); memFree(smFocusCommand); smFocusCommand = NULL; } mrRenderMainScreen = TRUE; soundEvent(NULL, UI_SoundOfSpace); } else { //else the transition has already been made if (!smFocus && smZoomTime > 0.0f) { //if not at end of zoom in with no focus cameraCopyPositionInfo(&universe.mainCameraCommand.actualcamera, &smCamera); universe.mainCameraCommand.actualcamera.ignoreZoom = TRUE; } return; } } } else { smCurrentWorldPlaneColor = smWorldPlaneColor; smCurrentCameraDistance = smCamera.clipPlaneFar; } smViewportRegion->rect = smViewRectangle; if (piePointSpecMode != PSM_Idle) { smCurrentWorldPlaneColor = colMultiplyClamped(smCurrentWorldPlaneColor, smMovementWorldPlaneDim); } //perform some render-time monkey work of the camera position if (!smZoomingIn && !smZoomingOut) { //don't move the eye point if zooming uicDragX = uicDragY = 0; if (keyIsHit(ARRLEFT)) { //pan the camera with the cursor keys uicDragX -= smCursorPanX * frameTicks / (udword)taskFrequency; } if (keyIsHit(ARRRIGHT)) { uicDragX += smCursorPanX * frameTicks / (udword)taskFrequency; } if (keyIsHit(ARRUP)) { uicDragY -= smCursorPanY * frameTicks / (udword)taskFrequency; } if (keyIsHit(ARRDOWN)) { uicDragY += smCursorPanY * frameTicks / (udword)taskFrequency; } if (uicDragX != 0 || uicDragY != 0) { smPan(NULL, NULL); } //perform cubic spline interpolation of the panned camera point vecSub(rememberVec, smCamera.lookatpoint, smCameraLookatPoint); if (ABS(rememberVec.x) + ABS(rememberVec.y) + ABS(rememberVec.z) > smPanEvalThreshold) { //if there is any distance between pan point and camera point while (frameTicks) { rememberVec = smCamera.lookatpoint; EvalCubic(&smCamera.lookatpoint.x, &smCameraLookVelocity.x, smCameraLookatPoint.x, smPanTrack); EvalCubic(&smCamera.lookatpoint.y, &smCameraLookVelocity.y, smCameraLookatPoint.y, smPanTrack); EvalCubic(&smCamera.lookatpoint.z, &smCameraLookVelocity.z, smCameraLookatPoint.z, smPanTrack); vecSub(diffVec, smCamera.lookatpoint, rememberVec); vecAddTo(smCamera.eyeposition, diffVec); //pan the eyeposition with the lookatpoint frameTicks--; } } } //now on to the actual rendering code: cameraSetEyePosition(&smCamera); primModeClear2(); rndLightingEnable(FALSE); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); rgluPerspective(smCamera.fieldofview, rndAspectRatio, //set projection matrix smCamera.clipPlaneNear, smCamera.clipPlaneFar); glScalef(smProjectionScale, smProjectionScale, smProjectionScale); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); #if RND_CAMERA_OFFSET rgluLookAt(smCamera.eyeposition.x + RND_CameraOffsetX, smCamera.eyeposition.y, smCamera.eyeposition.z, smCamera.lookatpoint.x + RND_CameraOffsetX, smCamera.lookatpoint.y, smCamera.lookatpoint.z, smCamera.upvector.x, smCamera.upvector.y, smCamera.upvector.z); #else rgluLookAt(smCamera.eyeposition.x, smCamera.eyeposition.y, smCamera.eyeposition.z, smCamera.lookatpoint.x, smCamera.lookatpoint.y, smCamera.lookatpoint.z, smCamera.upvector.x, smCamera.upvector.y, smCamera.upvector.z); #endif glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *)(&rndCameraMatrix)); glGetFloatv(GL_PROJECTION_MATRIX, (GLfloat *)(&rndProjectionMatrix)); //Draw the BTG background glPushMatrix(); glTranslatef(smCamera.eyeposition.x, smCamera.eyeposition.y, smCamera.eyeposition.z); rndBackgroundRender(BG_RADIUS, &smCamera, FALSE); //render the background glPopMatrix(); lightSetLighting(); rndLightingEnable(TRUE); //render all worlds in the universe for (index = 0; index < UNIV_NUMBER_WORLDS; index++) { if (universe.world[index] != NULL) { if (universe.world[index]->objtype == OBJ_DerelictType) { rndRenderAHomeworld(&smCamera, universe.world[index]); } } else { break; } } //update and draw all the sensors manager blobs smRenderCount++; if (smRenderCount >= smBlobUpdateRate) { smRenderCount = 0; } if (smGhostMode) { sensorLevel = 2; } else { sensorLevel = universe.curPlayerPtr->sensorLevel; } glGetFloatv(GL_MODELVIEW_MATRIX, (GLfloat *)(&rndCameraMatrix)); glGetFloatv(GL_PROJECTION_MATRIX, (GLfloat *)(&rndProjectionMatrix)); selectedBlob = smBlobsDraw(&smCamera, &universe.collBlobList, &rndCameraMatrix, &rndProjectionMatrix, universe.curPlayerPtr->sensorLevel); if (piePointSpecMode != PSM_Idle) { //draw point spec mrCamera = &smCamera; //point spec draw uses mrCamera pieLineDrawCallback = NULL; piePlaneDrawCallback = piePlaneDraw; pieMovementCursorDrawCallback = pieMovementCursorDraw; piePointSpecDraw(); //draw the movement mechanism } primModeSet2(); //draw the tactical overlay, if applicable if (smTacticalOverlay) { #if !TO_STANDARD_COLORS if (!singlePlayerGame) { //only print player names if multi-player game is underway smPlayerNamesDraw(&smViewRectangle); //draw the list of player names } #endif smHotkeyGroupsDraw(); } if (smHoldRight == smNULL && smHoldLeft == smNULL) { smCursorTextDraw(&smViewRectangle, selectedBlob, universe.curPlayerPtr->sensorLevel); } if (smHoldLeft == smSelectHold) //and then draw the current selection progress { primRectOutline2(&smSelectionRect, 1, TW_SELECT_BOX_COLOR); } if (nisStatic[NIS_SMStaticIndex] != NULL) { nisStaticDraw(nisStatic[NIS_SMStaticIndex]); } } /*----------------------------------------------------------------------------- Name : smNULL Description : NULL logic handler for when the user's not doing anything with the sensors manager. Inputs : void Outputs : void Return : void ----------------------------------------------------------------------------*/ void smNULL(void) { ; } /*----------------------------------------------------------------------------- Name : mrSelectHold Description : Function for dragging a selection box Inputs : Outputs : Return : ----------------------------------------------------------------------------*/ void smSelectHold(void) { if (ABS(mouseCursorX() - mrOldMouseX) >= selClickBoxWidth || ABS(mouseCursorY() - mrOldMouseY) >= selClickBoxHeight) { //if mouse has moved from anchor point mrSelectRectBuild(&smSelectionRect, mrOldMouseX, mrOldMouseY);//create a selection rect selRectNone(); } else { //else mouse hasn't moved far enough smSelectionRect.x0 = smSelectionRect.x1 = //select nothing smSelectionRect.y0 = smSelectionRect.y1 = 0; selRectNone(); } } /*----------------------------------------------------------------------------- Name : smCullAndFocusSelecting Description : Culls the current selection list to a reasonable size and focuses on it. Inputs : void Outputs : Return : void ----------------------------------------------------------------------------*/ void smCullAndFocusSelecting(void) { sdword index, nToFocusOn; vector centre = {0.0f, 0.0f, 0.0f}; if ((tutorial==TUTORIAL_ONLY) && !tutEnable.bSensorsClose) { return; } nToFocusOn = ccFocusCullRadiusMean((FocusCommand *)&selSelecting, smFocusRadius * smFocusRadius, &centre); if (nToFocusOn == 0) { //nothing to focus on return; } //now we have a full listing of what we can focus on. Let's focus on it. smFocus = TRUE; smFocusCommand = memAlloc(ccFocusSize(selSelecting.numTargets), "SensorsMultiFocus", 0); for (index = 0; index < selSelecting.numTargets; index++) { smFocusCommand->ShipPtr[index] = (Ship *)selSelecting.TargetPtr[index]; } smFocusCommand->numShips = selSelecting.numTargets; dbgAssertOrIgnore(!smZoomingOut); smZoomingIn = TRUE; /* call the sound event for closing the Sensors manager */ soundEvent(NULL, UI_SensorsExit); smFocusTransition = FALSE; smEyeEnd = smCamera.eyeposition; smLookEnd = smCamera.lookatpoint; smLookStart = centre; vecSub(smEyeStart, smLookEnd, smEyeEnd); vecNormalize(&smEyeStart); dbgAssertOrIgnore(smEyeStart.x < (real32)1e19 && smEyeStart.x > (real32)-1e19); vecMultiplyByScalar(smEyeStart, CAMERA_FOCUSFAR_DISTANCE); vecSub(smEyeStart, smLookStart, smEyeStart); smInitialDistance = smCamera.distance;//remember zoom-back distance for next time selRectNone(); //now create a render list as it will be when fully zoomed in smTempCamera.lookatpoint = smLookStart; smTempCamera.eyeposition = smEyeStart; mrCamera = &smTempCamera; univUpdateRenderList(); dbgAssertOrIgnore(smEyeStart.x < (real32)1e19 && smEyeStart.x > (real32)-1e19); //the player will get kicked into the sensors manager after several seconds waiting //with the camera nowhere near their ships. This is a security "anti-spy" measure. //If when kicked into the SM the player focuses on their own ships explicitly, we //don't want them to focus on their mothership, rather on the ships they specified. smFocusOnMothershipOnClose = FALSE; } /*----------------------------------------------------------------------------- Name : smViewportProcess Description : process messages for the main viewport of the sensors manager. Inputs : standard region callback parameters Outputs : .. Return : .. ----------------------------------------------------------------------------*/ udword smViewportProcess(regionhandle region, sdword ID, udword event, udword data) { // Ship *ship; // void *a, *b; if ((smZoomingIn)||(smZoomingOut)) { return 0; } switch (event) { case RPE_HoldLeft: smHoldLeft(); //call current hold function break; case RPE_HoldRight: smHoldRight(); //call current hold function break; case RPE_PressLeft: mouseClipToRect(&smViewRectangle); if (smHoldRight == smNULL && (!smFleetIntel)) { smClicking = TRUE; } if (smHoldRight == smNULL && (!smFleetIntel)) { mrOldMouseX = mouseCursorX(); //store anchor point mrOldMouseY = mouseCursorY(); smHoldLeft = smSelectHold; //set to select mode smSelectionRect.x0 = smSelectionRect.x1 = //select nothing smSelectionRect.y0 = smSelectionRect.y1 = 0; } break; case RPE_ReleaseLeft: if ((piePointSpecMode & (PSM_XY | PSM_Z)) != 0) { //if specified a point vector destination; dbgAssertOrIgnore(!smFleetIntel); MakeShipsMobile((SelectCommand *)&selSelected); if (selSelected.numShips > 0) { if (piePointSpecZ != 0.0f) { //if a height was specified destination = pieHeightPoint; } else { destination = piePlanePoint; //else move to point on plane } /** !!!! We should put the speech event AFTER incase the movement destination is invalid...in the probes case this could be often...very often **/ /** Done :) **/ /** Hooray !! **/ if (!(isnan((double)destination.x) || isnan((double)destination.x) || isnan((double)destination.x))) { if(mrNeedProbeHack()) { //looks like we need a little probe hacksy poo here too clWrapMove(&universe.mainCommandLayer,(SelectCommand *)&selSelected,selCentrePoint,destination); speechEventFleetSpec(selSelected.ShipPtr[0], COMM_F_Probe_Deployed, 0, universe.curPlayerIndex); } else { //move normally if(MP_HyperSpaceFlag) { vector distancevec; real32 cost; //we're in hyperspace pieplate mode! vecSub(distancevec,selCentrePoint,destination); cost = hyperspaceCost(fsqrt(vecMagnitudeSquared(distancevec)),(SelectCommand *)&selSelected); if(universe.curPlayerPtr->resourceUnits < ((sdword)cost)) { //can't afford it! //good speech event? if (battleCanChatterAtThisTime(BCE_CannotComply, selSelected.ShipPtr[0])) { battleChatterAttempt(SOUND_EVENT_DEFAULT, BCE_CannotComply, selSelected.ShipPtr[0], SOUND_EVENT_DEFAULT); } } else { //make unselectable in wrap function clWrapMpHyperspace(&universe.mainCommandLayer,(SelectCommand *)&selSelected,selCentrePoint,destination); } } else { //normal pieplate movement clWrapMove(&universe.mainCommandLayer,(SelectCommand *)&selSelected,selCentrePoint,destination); if (selSelected.ShipPtr[0]->shiptype == Mothership) { speechEventFleetSpec(selSelected.ShipPtr[0], COMM_F_MoShip_Move, 0, universe.curPlayerIndex); } else { speechEvent(selSelected.ShipPtr[0], COMM_Move, 0); } } } //untoggle correct button! if(MP_HyperSpaceFlag) { feToggleButtonSet(SM_Hyperspace, FALSE); } else { feToggleButtonSet(SM_Dispatch, FALSE); } } } // piePointSpecMode = PSM_Idle; //no more selecting piePointModeOnOff(); MP_HyperSpaceFlag = FALSE; //for now.. } else if (smClicking && !smFleetIntel) { Ship *clickedOn = NULL; if (ABS(mouseCursorX() - mrOldMouseX) < selClickBoxWidth && ABS(mouseCursorY() - mrOldMouseY) < selClickBoxHeight) { //if mouse has moved much smSelectionRect.x0 = mouseCursorX() - smSelectionWidth / 2; smSelectionRect.x1 = mouseCursorX() + smSelectionWidth / 2; smSelectionRect.y0 = mouseCursorY() - smSelectionHeight / 2; smSelectionRect.y1 = mouseCursorY() + smSelectionHeight / 2; clickedOn = selSelectionClick(universe.SpaceObjList.head, &smCamera, mouseCursorX(), mouseCursorY(), FALSE, FALSE); if (clickedOn != NULL) { if (clickedOn->playerowner != universe.curPlayerPtr && (!smGhostMode)) { clickedOn = FALSE; } } } else { mrSelectRectBuild(&smSelectionRect, mrOldMouseX, mrOldMouseY);//create a selection rect } if (smHoldRight == smNULL) { if (smGhostMode) { selRectDragAnybodyAnywhere(&smCamera, &smSelectionRect);//and select anything } else { // selRectDragAnywhere(&smCamera, &smSelectionRect);//and select anything selRectDragAnybodyAnywhere(&smCamera, &smSelectionRect);//and select anything MakeShipsFriendlyAndAlliesShips((SelectCommand *)&selSelecting, universe.curPlayerPtr); makeShipsNotBeDisabled((SelectCommand *)&selSelecting); } if (clickedOn != NULL) { if(!(clickedOn->flags & SOF_Disabled)) { selSelectionAddSingleShip((MaxSelection *)(&selSelecting), clickedOn); } } smCullAndFocusSelecting(); } } mouseClipToRect(NULL); smHoldLeft = smNULL; smClicking = FALSE; break; case RPE_PressRight: #ifdef _LINUX_FIX_ME mouseClipToRect(&smViewRectangle); #endif smHoldLeft = smNULL; smHoldRight = mrCameraMotion; mrOldMouseX = mouseCursorX(); //save current mouse location for later restoration mrOldMouseY = mouseCursorY(); mouseCursorHide(); //hide cursor and move to centre of the screen mousePositionSet(MAIN_WindowWidth / 2, MAIN_WindowHeight / 2); mrMouseHasMoved = 0; //mouse hasn't moved yet region->rect.x0 = region->rect.y0 = 0; //make it's rectangle full-screen region->rect.x1 = MAIN_WindowWidth; region->rect.y1 = MAIN_WindowHeight; smClicking = FALSE; piePointModePause(TRUE); //pause the point spec mode break; case RPE_ReleaseRight: mouseClipToRect(NULL); if (smHoldRight == mrCameraMotion) { //if in camera movement mode mousePositionSet(mrOldMouseX, mrOldMouseY); //restore mouse position mouseCursorShow(); //show mouse cursor smHoldRight = smNULL; //idle mode } //region->rect = smViewRectangle; //restore origional rectangle piePointModePause(FALSE); break; case RPE_WheelUp: wheel_up = TRUE; break; case RPE_WheelDown: wheel_down = TRUE; break; case RPE_KeyDown: if (smZoomingOut) { //if sensors manager is just starting break; //don't process key clicks } switch (ID) { case SHIFTKEY: if (smHoldRight != mrCameraMotion) { piePointModeToggle(TRUE); } break; case MMOUSE_BUTTON: case FKEY: if (!smFleetIntel) { selSelectionCopy((MaxAnySelection *)&selSelecting,(MaxAnySelection *)&selSelected); smCullAndFocusSelecting(); } break; #if SM_TOGGLE_SENSOR_LEVEL case LKEY: smToggleSensorsLevel(); break; #endif case ZEROKEY: case ONEKEY: case TWOKEY: case THREEKEY: case FOURKEY: case FIVEKEY: case SIXKEY: case SEVENKEY: case EIGHTKEY: case NINEKEY: if (!smFleetIntel) { if (keyIsHit(ALTKEY) || keyIsHit(RALTKEY)) { //alt-# select and focus on a hot key group altCase: if (selHotKeyGroup[NUMKEYNUM(ID)].numShips != 0) { selSelectionCopy((MaxAnySelection *)&selSelected,(MaxAnySelection *)&selHotKeyGroup[NUMKEYNUM(ID)]); selSelectionCopy((MaxAnySelection *)&selSelecting,(MaxAnySelection *)&selSelected); if(MP_HyperSpaceFlag) { makeSelectionHyperspaceCapable((SelectCommand *)&selSelected); } smCullAndFocusSelecting(); #if SM_VERBOSE_LEVEL >= 2 dbgMessagef("Hot key group %d selected and focused upon.", NUMKEYNUM(ID)); #endif } } else if (ID == mrLastKeyPressed && universe.totaltimeelapsed <= mrLastKeyTime + mrNumberDoublePressTime) { //double-#: focus on hot-key group tutGameMessage("KB_GroupSelectFocus"); goto altCase; //same as alt-# } else { //plain# select a hot key group if (selHotKeyGroup[NUMKEYNUM(ID)].numShips != 0) { tutGameMessage("KB_GroupSelect"); selSelectHotKeyGroup(&selHotKeyGroup[NUMKEYNUM(ID)]); selHotKeyNumbersSet(NUMKEYNUM(ID)); #if SEL_ERROR_CHECKING selHotKeyGroupsVerify(); #endif if(MP_HyperSpaceFlag) { makeSelectionHyperspaceCapable((SelectCommand *)&selSelected); } ioUpdateShipTotals(); if (selSelected.numShips > 0) { soundEvent(NULL, UI_Click); speechEvent(selHotKeyGroup[NUMKEYNUM(ID)].ShipPtr[0], COMM_AssGrp_Select, NUMKEYNUM(ID)); } } } } break; } mrLastKeyPressed = ID; mrLastKeyTime = universe.totaltimeelapsed; break; case RPE_KeyUp: if (smZoomingOut) { //if sensors manager is just starting break; //don't process key clicks } switch (ID) { case SHIFTKEY: if (smHoldRight != mrCameraMotion) { piePointModeToggle(FALSE); } break; } break; #if SM_VERBOSE_LEVEL >= 1 default: dbgMessagef("smViewportProcess: unimplemented or unsupported event 0x%x. ID 0x%x, data 0x%x", event, ID, data); #endif } return(0); } /*----------------------------------------------------------------------------- Name : various Description : Processor callbacks for FE buttons Inputs : standard FE callback parameters Outputs : Return : void ----------------------------------------------------------------------------*/ void smDispatch(char *name, featom *atom) { #if SM_VERBOSE_LEVEL >= 1 dbgMessage("smDispatch"); #endif if (smHoldRight == smNULL) { //cannot bring up MM with RMB held down if (!smFleetIntel && ((!(tutorial==TUTORIAL_ONLY)) || tutEnable.bMove)) { if(mrNeedProbeHack()) { mrProbeHack(); } else { mrRemoveAllProbesFromSelection(); if(MP_HyperSpaceFlag) { MP_HyperSpaceFlag = FALSE; } else { if (piePointSpecMode == PSM_Idle) { //if bringing up the MM makeShipsControllable((SelectCommand *)&selSelected,COMMAND_MP_HYPERSPACING); makeShipsNotIncludeSinglePlayerMotherships((SelectCommand *)&selSelected); if(selSelected.numShips > 0) { //if there are ships we can control piePointModeOnOff(); } } else { //always allow the MM to be turned off piePointModeOnOff(); } } } } } feToggleButtonSet(name, piePointSpecMode != PSM_Idle); } void smUpdateHyperspaceStatus(bool32 goForLaunch) { mrUpdateHyperspaceStatus(goForLaunch); if (smHyperspaceRegion == NULL) { return; } if (goForLaunch) { bitClear(smHyperspaceRegion->status, RSF_RegionDisabled); } else { bitSet(smHyperspaceRegion->status, RSF_RegionDisabled); } } void smHyperspace(char *name, featom *atom) { regionhandle region = (regionhandle)atom->region; #if SM_VERBOSE_LEVEL >= 1 dbgMessage("smHyperspace"); #endif if (FEFIRSTCALL(atom)) { smHyperspaceRegion = region; if (singlePlayerGame) { if (singlePlayerGameInfo.playerCanHyperspace) { bitClear(region->status, RSF_RegionDisabled); } else { bitSet(region->status, RSF_RegionDisabled); } } else { //check research capabilities... //if not researched...black out button! if(!bitTest(tpGameCreated.flag,MG_Hyperspace)) { bitSet(region->status, RSF_RegionDisabled); } //multiplayer Hyperspace initial Call! } } else if (FELASTCALL(atom)) { smHyperspaceRegion = NULL; //check if movement plate for HYPERSPACE is up... //close it... if(!singlePlayerGame) { if(!bitTest(tpGameCreated.flag,MG_Hyperspace)) { return; } } if (piePointSpecMode!=PSM_Idle && MP_HyperSpaceFlag) { soundEvent(NULL, UI_MovementGUIoff); MP_HyperSpaceFlag = FALSE; piePointModeOnOff(); } } else { if(!singlePlayerGame) { if(!bitTest(tpGameCreated.flag,MG_Hyperspace)) { return; } } if (singlePlayerGame && singlePlayerGameInfo.playerCanHyperspace) { spHyperspaceButtonPushed(); } else { if (!smFleetIntel) { if(MP_HyperSpaceFlag) { MP_HyperSpaceFlag = FALSE; piePointModeOnOff(); soundEvent(NULL, UI_MovementGUIoff); } else { makeShipsControllable((SelectCommand *)&selSelected,COMMAND_MP_HYPERSPACING); makeSelectionHyperspaceCapable((SelectCommand *)&selSelected); if(selSelected.numShips == 0) { //removed all ships! //if normal gui up..bring it down! if (piePointSpecMode != PSM_Idle) { //turn it off! soundEvent(NULL, UI_MovementGUIoff); MP_HyperSpaceFlag = FALSE; piePointModeOnOff(); } } else { MP_HyperSpaceFlag = TRUE; if (piePointSpecMode == PSM_Idle) { //plate isn't up...turn it on! piePointModeOnOff(); } } } } } } } void smTacticalOverlayToggle(char *name, featom *atom) { smTacticalOverlay ^= TRUE; #if SM_VERBOSE_LEVEL >= 1 dbgMessagef("smTacticalOverlayToggle: %s", smTacticalOverlay ? "ON" : "OFF"); #endif } void smNonResourceToggle(char *name, featom *atom) { smNonResources ^= TRUE; #if SM_VERBOSE_LEVEL >= 1 dbgMessagef("smNonResourceToggle: %s", smNonResources ? "ON" : "OFF"); #endif } void smResourceToggle(char *name, featom *atom) { smResources ^= TRUE; #if SM_VERBOSE_LEVEL >= 1 dbgMessagef("smResourceToggle: %s", smResources ? "ON" : "OFF"); #endif } void smSensorsClose(char *name, featom *atom) { vector direction,dist; real32 dStart; if ((tutorial==TUTORIAL_ONLY) && !tutEnable.bSensorsClose) { return; } // dbgAssertOrIgnore(!smFleetIntel); if (smZoomingIn || smZoomingOut) { //if hit while already zooming return; } #if SM_VERBOSE_LEVEL >= 1 dbgMessage("smSensorsClose"); #endif if(smFocusOnMothershipOnClose) { ccFocusOnMyMothership(&universe.mainCameraCommand); smFocusOnMothershipOnClose = FALSE; } //!!! Jason: set the value of smLookStart to the centre of the focussed ships. ccLockOnTargetNow(&universe.mainCameraCommand); smLookStart = universe.mainCameraCommand.actualcamera.lookatpoint; smEyeStart = universe.mainCameraCommand.actualcamera.eyeposition; vecSub(direction, smEyeStart, smLookStart); dStart = fmathSqrt(vecMagnitudeSquared(direction)); smEyeEnd = smCamera.eyeposition; smLookEnd = smCamera.lookatpoint; vecSub(direction, smLookEnd, smEyeEnd); vecNormalize(&direction); vecMultiplyByScalar(direction, dStart); vecSub(smEyeStart, smLookStart, direction); dbgAssertOrIgnore(!smZoomingOut); smZoomingIn = TRUE; /* call the sound event for closing the Sensors manager */ soundEvent(NULL, UI_SensorsExit); smFocusTransition = FALSE; smInitialDistance = smCamera.distance; smFocus = FALSE; //now create a render list as it will be when fully zoomed in smTempCamera.lookatpoint = smLookStart; smTempCamera.eyeposition = smEyeStart; mrCamera = &smTempCamera; univUpdateRenderList(); dbgAssertOrIgnore(smEyeStart.x < (real32)1e19 && smEyeStart.x > (real32)-1e19); //Probe Hack Start ****************** if(mrNeedProbeHack()) { if(piePointSpecMode != PSM_Idle) { //turn off pie plate movement mech. MP_HyperSpaceFlag = FALSE; piePointModeOnOff(); } } // check to see if pieplate active if it is and out of range turn it off. if (piePointSpecMode!=PSM_Idle) { selCentrePointCompute(); vecSub(dist,selCentrePoint,universe.mainCameraCommand.actualcamera.lookatpoint); if (vecMagnitudeSquared(dist) >= MAX_MOVE_DISTANCE) { MP_HyperSpaceFlag = FALSE; piePointModeOnOff(); } } //Probe Hack END ****************** MP_HyperSpaceFlag = FALSE; bitClear(tbDisable,TBDISABLE_SENSORS_USE); } void smSensorsSkip(char *name, featom *atom) { subMessageEnded = 2; //the fleet intel thing was skipped speechEventActorStop(ACTOR_ALL_ACTORS, smSkipFadeoutTime); subTitlesFadeOut(&subRegion[STR_LetterboxBar], smSkipFadeoutTime); } void smCancelDispatch(char *name, featom *atom) { #if SM_VERBOSE_LEVEL >= 1 dbgMessage("smCancelDispatch"); #endif feToggleButtonSet(SM_TacticalOverlay, FALSE); piePointSpecMode = SPM_Idle; } #if SM_TOGGLE_SENSOR_LEVEL void smToggleSensorsLevel(void) { universe.curPlayerPtr->sensorLevel++; if (universe.curPlayerPtr->sensorLevel > 2) { universe.curPlayerPtr->sensorLevel = 0; } #if SM_VERBOSE_LEVEL >= 1 dbgMessagef("smToggleSensorsLevel: level set to %d", universe.curPlayerPtr->sensorLevel); #endif } #endif //SM_TOGGLE_SENSOR_LEVEL void smCancelMoveOrClose(char *name, featom *atom) { MP_HyperSpaceFlag = FALSE; //no matter what, set to FALSE if (piePointSpecMode != PSM_Idle) { piePointModeOnOff(); soundEvent(NULL, UI_MovementGUIoff); } else { smSensorsClose(SM_Close, atom); } } /*============================================================================= Functions: =============================================================================*/ /*----------------------------------------------------------------------------- Name : smStartup Description : Start the sensors manager module. Inputs : void Outputs : adds some callbacks, loads some stuff etc, etc... Return : void ----------------------------------------------------------------------------*/ fecallback smCallbacks[] = { {smDispatch, SM_Dispatch}, {smHyperspace, SM_Hyperspace}, {smTacticalOverlayToggle, SM_TacticalOverlay}, {smNonResourceToggle, SM_NonResource}, {smResourceToggle, SM_Resource}, {smSensorsClose, SM_Close}, {smSensorsSkip, SM_Skip}, {smCancelDispatch, SM_CancelDispatch}, {smPan, SM_Pan}, {smCancelMoveOrClose, SM_CancelMoveOrClose}, {NULL, NULL}, }; void smStartup(void) { scriptSet(NULL, "sensors.script", smTweaks); feDrawCallbackAdd(SM_ViewportName, smViewportRender); //add render callback feCallbackAddMultiple(smCallbacks); cameraInit(&smCamera, SM_InitialCameraDist); smUpdateParameters(); smHoldRight = smNULL; smHoldLeft = smNULL; MP_HyperSpaceFlag = FALSE; //set to FALSE...should manage itself from here on... // listInit(&smBlobList); } /*----------------------------------------------------------------------------- Name : smUpdateParameters Description : Update the sensors manager parameters after a level has loaded some sensors parameters. Inputs : Outputs : Return : void ----------------------------------------------------------------------------*/ void smUpdateParameters(void) { smCamera.clipPlaneNear = smZoomMin / smZoomMinFactor; smCamera.clipPlaneFar = smZoomMax * smZoomMaxFactor; smCamera.closestZoom = smZoomMin; smCamera.farthestZoom = smZoomMax; smCamera.distance = smInitialDistance; smCircleBorder = SM_CircleBorder; //ignore the value set in the level file } /*----------------------------------------------------------------------------- Name : smShutdown Description : Shut down the sensors manager module. Inputs : void Outputs : Return : void ----------------------------------------------------------------------------*/ void smShutdown(void) { } /*----------------------------------------------------------------------------- Name : smSensorsBegin Description : Starts the sensors manager Inputs : name, atom - ignored Outputs : Return : void ----------------------------------------------------------------------------*/ void smSensorsBegin(char *name, featom *atom) { regionhandle baseRegion, reg; sdword index, diff; fescreen *screen; featom *pAtom; sdword smViewExpandLeft; sdword smViewExpandRight; sdword smViewExpandTop; sdword smViewExpandBottom; char *screenName; bitClear(ghMainRegion->status, RSF_MouseInside); mrHoldLeft = mrHoldRight = mrNULL; //prevent a wierd bug if(smSensorsDisable || ((tutorial==TUTORIAL_ONLY) && !tutEnable.bSensorsManager)) { return; } ioSaveState = ioDisable(); tbSensorsHook(); screenName = smFleetIntel ? SM_FleetIntelScreenName : SM_ScreenName; screen = feScreenFind(screenName); smBaseRegion = baseRegion = feScreenStart(ghMainRegion, screenName); //now find the user region the sensors manager is rendered in reg = baseRegion->child; smViewportRegion = NULL; for (index = 1; index < screen->nAtoms; index++) { // reg = (regionhandle)screen->atoms[index].region; regVerify(reg); if (((featom *)reg->userID)->pData == (ubyte *)smViewportRender) //if this is a user region { smBackgroundColor = ((featom *)reg->userID)->contentColor; // glClearColor(colUbyteToReal(colRed(smBackgroundColor)), // colUbyteToReal(colGreen(smBackgroundColor)), // colUbyteToReal(colBlue(smBackgroundColor)), 1.0f); smViewportRegion = reg; //this must be the region break; } reg = reg->next; } dbgAssertOrIgnore(smViewportRegion != NULL); regFunctionSet(smViewportRegion, (regionfunction) smViewportProcess); regFilterSet(smViewportRegion, SM_ViewportFilter); smViewRectangle = smViewportRegion->rect; /* index = 640 - (smViewRectangle.x1 - smViewRectangle.x0); index >>= 1; index++; smViewRectangle.x0 = index; smViewRectangle.x1 = MAIN_WindowWidth - index; */ //now let's go through all the regions and build lists of regions outside the //main viewport. These regions are to scroll onto the screen during the zoom. reg = baseRegion->child; smScrollListTop = smScrollListLeft = smScrollListRight = smScrollListBottom = NULL; smScrollCountLeft = smScrollCountTop = smScrollCountRight = smScrollCountBottom = 0; smScrollDistLeft = smScrollDistTop = smScrollDistRight = smScrollDistBottom = 0; smScrollLeft = smScrollTop = smScrollRight = smScrollBottom = 0; for (index = 1; index < screen->nAtoms; index++, reg = reg->next) { // reg = (regionhandle)screen->atoms[index].region; regVerify(reg); pAtom = (featom *)reg->userID; if (reg->rect.x1 <= smViewportRegion->rect.x0) { //if off left smScrollCountLeft++; smScrollListLeft = memRealloc(smScrollListLeft, smScrollCountLeft * sizeof(region**), "ScrollListLeft", 0); smScrollListLeft[smScrollCountLeft - 1] = reg; continue; } if (reg->rect.y1 <= smViewportRegion->rect.y0) { //if off top smScrollCountTop++; smScrollListTop = memRealloc(smScrollListTop, smScrollCountTop * sizeof(region**), "ScrollListTop", 0); smScrollListTop[smScrollCountTop - 1] = reg; continue; } if (reg->rect.x0 >= smViewportRegion->rect.x1) { //if off right smScrollCountRight++; smScrollListRight = memRealloc(smScrollListRight, smScrollCountRight * sizeof(region**), "ScrollListRight", 0); smScrollListRight[smScrollCountRight - 1] = reg; continue; } if (reg->rect.y0 >= smViewportRegion->rect.y1) { //if off bottom smScrollCountBottom++; smScrollListBottom = memRealloc(smScrollListBottom, smScrollCountBottom * sizeof(region**), "ScrollListBottom", 0); smScrollListBottom[smScrollCountBottom - 1] = reg; continue; } } //compute pan distance to get these rectangles to work in high-rez smViewExpandLeft = (MAIN_WindowWidth - 640) / 2; smViewExpandRight = (MAIN_WindowWidth - 640) - smViewExpandLeft; smViewExpandTop = (MAIN_WindowHeight - 480) / 2; smViewExpandBottom = (MAIN_WindowHeight - 480) - smViewExpandTop; //let's figure out how far we'll have to scroll each of these lists for (index = 0; index < smScrollCountLeft; index++) { smScrollDistLeft = max(smScrollDistLeft, smScrollListLeft[index]->rect.x1 - smScrollListLeft[index]->rect.x0); } for (index = 0; index < smScrollCountTop; index++) { if (smFleetIntel && index == smScrollCountTop - 1) { //consider the last region as a letterbox bar dbgAssertOrIgnore(smScrollListTop[index]->drawFunction == feStaticRectangleDraw); diff = smScrollListTop[index]->rect.y1 - smScrollListTop[index]->rect.y0; diff = (diff) * MAIN_WindowHeight / 480 - diff; smScrollListTop[index]->rect.y1 += diff; smViewportRegion->rect.y0 += diff; smViewRectangle.y0 += diff; } smScrollDistTop = max(smScrollDistTop, smScrollListTop[index]->rect.y1 - smScrollListTop[index]->rect.y0); } for (index = 0; index < smScrollCountRight; index++) { smScrollDistRight = max(smScrollDistRight, smScrollListRight[index]->rect.x1 - smScrollListRight[index]->rect.x0); } for (index = 0; index < smScrollCountBottom; index++) { if (smFleetIntel && index == smScrollCountBottom - 1) { //consider the last region as a letterbox bar dbgAssertOrIgnore(smScrollListBottom[index]->drawFunction == feStaticRectangleDraw); diff = smScrollListBottom[index]->rect.y1 - smScrollListBottom[index]->rect.y0; diff = (diff) * MAIN_WindowHeight / 480 - diff; smScrollListBottom[index]->rect.y0 -= diff; smViewportRegion->rect.y1 -= diff; smViewRectangle.y1 -= diff; } smScrollDistBottom = max(smScrollDistBottom, smScrollListBottom[index]->rect.y1 - smScrollListBottom[index]->rect.y0); } //unt finally, let's scroll them far enough to be off-screen for (index = 0; index < smScrollCountLeft; index++) { if (smScrollListLeft[index]->rect.y0 <= smViewRectangle.y0) { smScrollListLeft[index]->rect.y0 -= smViewExpandTop; } if (smScrollListLeft[index]->rect.y1 >= smViewRectangle.y1) { smScrollListLeft[index]->rect.y1 += smViewExpandBottom; } regRegionScroll(smScrollListLeft[index], -smScrollDistLeft - smViewExpandLeft, 0); } for (index = 0; index < smScrollCountTop; index++) { if (smScrollListTop[index]->rect.x0 <= smViewRectangle.x0) { smScrollListTop[index]->rect.x0 -= smViewExpandLeft; } if (smScrollListTop[index]->rect.x1 >= smViewRectangle.x1) { smScrollListTop[index]->rect.x1 += smViewExpandRight; } regRegionScroll(smScrollListTop[index], 0, -smScrollDistTop - smViewExpandTop); } for (index = 0; index < smScrollCountRight; index++) { if (smScrollListRight[index]->rect.y0 <= smViewRectangle.y0) { smScrollListRight[index]->rect.y0 -= smViewExpandTop; } if (smScrollListRight[index]->rect.y1 >= smViewRectangle.y1) { smScrollListRight[index]->rect.y1 += smViewExpandBottom; } regRegionScroll(smScrollListRight[index], smScrollDistRight + smViewExpandRight, 0); } for (index = 0; index < smScrollCountBottom; index++) { if (smScrollListBottom[index]->rect.x0 <= smViewRectangle.x0) { smScrollListBottom[index]->rect.x0 -= smViewExpandLeft; } if (smScrollListBottom[index]->rect.x1 >= smViewRectangle.x1) { smScrollListBottom[index]->rect.x1 += smViewExpandRight; } regRegionScroll(smScrollListBottom[index], 0, smScrollDistBottom + smViewExpandBottom); } //set the view rectangle to full screen size, to be scaled as we go zoom back smViewRectangle.x0 -= smScrollDistLeft + smViewExpandLeft; smViewRectangle.y0 -= smScrollDistTop + smViewExpandTop; smViewRectangle.x1 += smScrollDistRight + smViewExpandRight; smViewRectangle.y1 += smScrollDistBottom + smViewExpandBottom; smViewportRegion->rect = smViewRectangle; smZoomTime = 0.0f; if (smInstantTransition && !smFleetIntel) { smCurrentZoomLength = 0.1f; smCurrentMainViewZoomLength = 0.05f; } else { smCurrentZoomLength = smZoomLength; smCurrentMainViewZoomLength = smMainViewZoomLength; } //figure out the start/end points for the camera animation smLookStart = universe.mainCameraCommand.actualcamera.lookatpoint; smEyeStart = universe.mainCameraCommand.actualcamera.eyeposition; //smLookEnd.x = smLookEnd.y = smLookEnd.z = 0.0f; smLookEnd = universe.mainCameraCommand.actualcamera.lookatpoint; smCameraLookatPoint = smLookEnd; smCameraLookVelocity.x = smCameraLookVelocity.y = smCameraLookVelocity.z = 0.0f; vecSub(smEyeEnd, smEyeStart, smLookStart); vecNormalize(&smEyeEnd); vecMultiplyByScalar(smEyeEnd, smInitialDistance); vecAddTo(smEyeEnd, smLookEnd); smZoomingIn = FALSE; smZoomingOut = TRUE; // mrRenderMainScreen = FALSE; feToggleButtonSet(SM_TacticalOverlay, smTacticalOverlay); feToggleButtonSet(SM_Resource , smResources); feToggleButtonSet(SM_NonResource , smNonResources); feToggleButtonSet(SM_Dispatch , piePointSpecMode != PSM_Idle); mouseClipToRect(NULL); smHoldLeft = smNULL; smHoldRight = smNULL; // bobListCreate(&smBlobProperties, &smBlobList, universe.curPlayerIndex); smSensorsActive = TRUE; soundEventStopSFX(0.5f); /* call the sound event for opening the Sensors manager */ soundEvent(NULL, UI_SensorsIntro); universe.dontUpdateRenderList = TRUE; smRenderCount = 0; //add any additional key messages the sensors manager will need regKeyChildAlloc(smViewportRegion, SHIFTKEY, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, SHIFTKEY); regKeyChildAlloc(smViewportRegion, MKEY, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, MKEY); regKeyChildAlloc(smViewportRegion, FKEY, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, FKEY); regKeyChildAlloc(smViewportRegion, MMOUSE_BUTTON, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, MMOUSE_BUTTON); regKeyChildAlloc(smViewportRegion, ARRLEFT, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, ARRLEFT ); regKeyChildAlloc(smViewportRegion, ARRRIGHT, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, ARRRIGHT); regKeyChildAlloc(smViewportRegion, ARRUP, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, ARRUP ); regKeyChildAlloc(smViewportRegion, ARRDOWN, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, ARRDOWN ); #if SM_TOGGLE_SENSOR_LEVEL regKeyChildAlloc(smViewportRegion, LKEY, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, LKEY); #endif for (index = FIRSTNUMKEY; index < FIRSTNUMKEY+10; index++) { regKeyChildAlloc(smViewportRegion, index, RPE_KeyUp | RPE_KeyDown, (regionfunction) smViewportProcess, 1, index); } mouseCursorShow(); cameraCopyPositionInfo(&smCamera, mrCamera); if (smFleetIntel) { //if we are in the fleet intel screen, no movement mechanism! piePointSpecMode = SPM_Idle; } bitSet(tbDisable,TBDISABLE_SENSORS_USE); } /*----------------------------------------------------------------------------- Name : smObjectDied Description : Called when an object dies, this function removes it from the sensors manager blob in which it exists. Inputs : object - object to delete Outputs : Return : void ----------------------------------------------------------------------------*/ void smObjectDied(void *object) { sdword index; // bobObjectDied(object,&smBlobList); //remove it from the focus command, if there is one. if (smFocusCommand) { for (index = 0; index < smFocusCommand->numShips; index++) { if ((SpaceObj *)smFocusCommand->ShipPtr[index] == object) { for (; index < smFocusCommand->numShips - 1; index++) { smFocusCommand->ShipPtr[index] = smFocusCommand->ShipPtr[index + 1]; } smFocusCommand->numShips--; if (smFocusCommand->numShips <= 0) { memFree(smFocusCommand); smFocusCommand = NULL; smFocus = FALSE; } return; } } } } /*============================================================================= Save Game Stuff: =============================================================================*/ void smSave(void) { SaveInfoNumber(Real32ToSdword(smDepthCueRadius)); SaveInfoNumber(Real32ToSdword(smDepthCueStartRadius)); SaveInfoNumber(Real32ToSdword(smCircleBorder)); SaveInfoNumber(Real32ToSdword(smZoomMax)); SaveInfoNumber(Real32ToSdword(smZoomMin)); SaveInfoNumber(Real32ToSdword(smZoomMinFactor)); SaveInfoNumber(Real32ToSdword(smZoomMaxFactor)); SaveInfoNumber(Real32ToSdword(smInitialDistance)); SaveInfoNumber(Real32ToSdword(smUniverseSizeX)); SaveInfoNumber(Real32ToSdword(smUniverseSizeY)); SaveInfoNumber(Real32ToSdword(smUniverseSizeZ)); SaveInfoNumber(smSensorWeirdness); } void smLoad(void) { sdword loadnum; loadnum = LoadInfoNumber(); smDepthCueRadius = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smDepthCueStartRadius = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smCircleBorder = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smZoomMax = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smZoomMin = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smZoomMinFactor = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smZoomMaxFactor = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smInitialDistance = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smUniverseSizeX = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smUniverseSizeY = SdwordToReal32(loadnum); loadnum = LoadInfoNumber(); smUniverseSizeZ = SdwordToReal32(loadnum); smSensorWeirdness = LoadInfoNumber(); smUpdateParameters(); }
0
0.836366
1
0.836366
game-dev
MEDIA
0.580325
game-dev
0.842367
1
0.842367
OpenHV/OpenHV
7,760
OpenRA.Mods.HV/Traits/BaseSpawnerParent.cs
#region Copyright & License Information /* * Copyright 2021-2025 The OpenHV Developers (see CREDITS) * This file is part of OpenHV, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. For more * information, see COPYING. */ #endregion using System; using System.Collections.Generic; using System.Linq; using OpenRA.Mods.Common.Traits; using OpenRA.Traits; namespace OpenRA.Mods.HV.Traits { // What to do when parent is killed or mind controlled public enum SpawnerChildDisposal { DoNothing, KillChildren, GiveChildrenToAttacker } public class BaseSpawnerChildEntry { public string ActorName = null; public Actor Actor = null; public BaseSpawnerChild SpawnerChild = null; public bool IsValid { get { return Actor != null && !Actor.IsDead; } } } [Desc("This actor can spawn actors.")] public class BaseSpawnerParentInfo : ConditionalTraitInfo { [ActorReference] [FieldLoader.Require] [Desc("Spawn these units.")] public readonly string[] Actors; [Desc("Child actors to contain upon creation. Set to -1 to start with full children.")] public readonly int InitialActorCount = -1; [Desc("Name of the armaments that grants the LaunchingCondition.", "The rate of fire of the dummy weapon determines the launch cycle as each shot.")] public readonly HashSet<string> ArmamentNames = ["primary"]; [Desc("What happens to the children when the parent is killed?")] public readonly SpawnerChildDisposal ChildDisposalOnKill = SpawnerChildDisposal.KillChildren; [Desc("What happens to the children when the parent is mind controlled?")] public readonly SpawnerChildDisposal ChildDisposalOnOwnerChange = SpawnerChildDisposal.GiveChildrenToAttacker; [Desc("Only spawn initial load of children?")] public readonly bool NoRegeneration = false; [Desc("Spawn all children at once when regenerating children, instead of one by one?")] public readonly bool SpawnAllAtOnce = false; [Desc("Spawn regeneration delay, in ticks")] public readonly int RespawnTicks = 150; public override void RulesetLoaded(Ruleset rules, ActorInfo ai) { base.RulesetLoaded(rules, ai); if (InitialActorCount > Actors.Length) throw new YamlException($"{nameof(InitialActorCount)} can't be larger than the actors defined! (Actor type: {ai.Name})"); if (InitialActorCount < -1) throw new YamlException($"{nameof(InitialActorCount)} must be -1 or non-negative. Actor type: {ai.Name}"); } public override object Create(ActorInitializer init) { return new BaseSpawnerParent(init, this); } } public class BaseSpawnerParent : ConditionalTrait<BaseSpawnerParentInfo>, INotifyKilled, INotifyOwnerChanged, INotifyActorDisposing { readonly Actor self; protected readonly BaseSpawnerChildEntry[] ChildEntries; IFacing facing; protected IReloadModifier[] reloadModifiers; public BaseSpawnerParent(ActorInitializer init, BaseSpawnerParentInfo info) : base(info) { self = init.Self; // Initialize child entries (doesn't instantiate the children yet) ChildEntries = CreateChildEntries(info); for (var i = 0; i < info.Actors.Length; i++) { var entry = ChildEntries[i]; entry.ActorName = info.Actors[i].ToLowerInvariant(); } } public virtual BaseSpawnerChildEntry[] CreateChildEntries(BaseSpawnerParentInfo info) { var childEntries = new BaseSpawnerChildEntry[info.Actors.Length]; for (var i = 0; i < childEntries.Length; i++) childEntries[i] = new BaseSpawnerChildEntry(); return childEntries; } protected override void Created(Actor self) { base.Created(self); facing = self.TraitOrDefault<IFacing>(); reloadModifiers = self.TraitsImplementing<IReloadModifier>().ToArray(); } /// <summary> /// Replenish destroyed children or create new ones from nothing. /// </summary> public void Replenish(Actor self, BaseSpawnerChildEntry[] childEntries) { if (Info.SpawnAllAtOnce) { foreach (var childentry in childEntries) if (!childentry.IsValid) Replenish(self, childentry); } else { var entry = SelectEntryToSpawn(childEntries); // All are alive and well. if (entry == null) return; Replenish(self, entry); } } /// <summary> /// Replenish one child entry. /// </summary> public virtual void Replenish(Actor self, BaseSpawnerChildEntry entry) { if (entry.IsValid) throw new InvalidOperationException("Replenish must not be run on a valid entry!"); // Some members are missing. Create a new one. var child = self.World.CreateActor(false, entry.ActorName, [new OwnerInit(self.Owner)]); InitializeChildEntry(child, entry); entry.SpawnerChild.LinkParent(entry.Actor, self, this); } /// <summary> /// Child entry initializer function. /// Override this function from derived classes to initialize their own specific stuff. /// </summary> public virtual void InitializeChildEntry(Actor child, BaseSpawnerChildEntry entry) { entry.Actor = child; entry.SpawnerChild = child.Trait<BaseSpawnerChild>(); } protected BaseSpawnerChildEntry SelectEntryToSpawn(BaseSpawnerChildEntry[] childEntries) { // If any thing is marked dead or null, that's a candidate. var candidates = childEntries.Where(m => !m.IsValid).ToList(); if (candidates.Count == 0) return null; return candidates.Random(self.World.SharedRandom); } void INotifyOwnerChanged.OnOwnerChanged(Actor self, Player oldOwner, Player newOwner) { OnOwnerChanged(self, oldOwner, newOwner); } public virtual void OnOwnerChanged(Actor self, Player oldOwner, Player newOwner) { self.World.AddFrameEndTask(w => { foreach (var childEntry in ChildEntries) if (childEntry.IsValid) childEntry.SpawnerChild.OnParentOwnerChanged(childEntry.Actor, oldOwner, newOwner, Info.ChildDisposalOnOwnerChange); }); } void INotifyActorDisposing.Disposing(Actor self) { // Just dispose them regardless of child disposal options. foreach (var childEntry in ChildEntries) if (childEntry.IsValid) childEntry.Actor.Dispose(); } public virtual void SpawnIntoWorld(Actor self, Actor child, WPos centerPosition) { var exit = self.RandomExitOrDefault(self.World, null); SetSpawnedFacing(child, exit); self.World.AddFrameEndTask(w => { if (self.IsDead) return; foreach (var notify in self.TraitsImplementing<INotifyExitCarrier>()) notify.Opening(self, child); var spawnOffset = WVec.Zero; if (exit != null) spawnOffset = exit.Info.SpawnOffset.Rotate(new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(64) - facing.Facing)); child.Trait<IPositionable>().SetCenterPosition(child, centerPosition + spawnOffset); var location = self.World.Map.CellContaining(centerPosition + spawnOffset); var move = child.Trait<IMove>(); child.QueueActivity(move.ReturnToCell(child)); child.QueueActivity(move.MoveTo(location, 2)); w.Add(child); }); } void SetSpawnedFacing(Actor spawned, Exit exit) { var facingOffset = facing?.Facing ?? WAngle.Zero; var exitFacing = exit?.Info.Facing ?? WAngle.Zero; var spawnFacing = spawned.TraitOrDefault<IFacing>(); if (spawnFacing != null) spawnFacing.Facing = facingOffset + exitFacing; } public virtual void OnChildKilled(Actor self, Actor child) { } void INotifyKilled.Killed(Actor self, AttackInfo e) { foreach (var childEntry in ChildEntries) if (childEntry.IsValid) childEntry.SpawnerChild.OnParentKilled(childEntry.Actor, e.Attacker, Info.ChildDisposalOnKill); } } }
0
0.927944
1
0.927944
game-dev
MEDIA
0.958567
game-dev
0.89579
1
0.89579
shawwn/noh
44,632
src/editor/c_foliagetool.cpp
// (C)2005 S2 Games // c_foliagetool.cpp // // Foliage Tool //============================================================================= //============================================================================= // Headers //============================================================================= #include "editor_common.h" #include "editor.h" #include "c_foliagetool.h" #include "../k2/c_brush.h" #include "../k2/c_vid.h" #include "../k2/c_texture.h" #include "../k2/c_scenemanager.h" #include "../k2/s_foliagetile.h" #include "../k2/c_uitrigger.h" #include "../k2/c_draw2d.h" #include "../k2/c_fontmap.h" #include "../k2/c_resourcemanager.h" //============================================================================= //============================================================================= // Declarations //============================================================================= CVAR_INT (le_foliageMode, FOLIAGE_AUTO); CVAR_INT (le_foliageLayer, 0); CVAR_FLOAT (le_foliageDensity, 16.0f); CVAR_FLOAT (le_foliageDensity2, 0.0f); CVAR_FLOAT (le_foliageSizeWidth, 64.0f); CVAR_FLOAT (le_foliageSizeWidth2, 64.0f); CVAR_FLOAT (le_foliageSizeHeight, 32.0f); CVAR_FLOAT (le_foliageSizeHeight2, 32.0f); CVAR_FLOAT (le_foliageSizeRandWidth, 0.0f); CVAR_FLOAT (le_foliageSizeRandWidth2, 0.0f); CVAR_FLOAT (le_foliageSizeRandHeight, 8.0f); CVAR_FLOAT (le_foliageSizeRandHeight2, 8.0f); CVAR_FLOAT (le_foliageScale, 1.0f); CVAR_FLOAT (le_foliageScale2, 0.0f); CVAR_FLOAT (le_foliageAuto, 1.0f); CVAR_FLOAT (le_foliageAuto2, 1.0f); CVAR_FLOAT (le_foliageBrushStrength, 50.0f); CVAR_BOOL (le_foliageDrawBrushInfluence, true); CVAR_FLOAT (le_foliageBrushInfluenceAlpha, 1.0f); CVAR_STRING (le_foliageTexture, "/world/foliage/textures/greengrass.tga"); CVAR_INT (le_foliageCrossQuads, 2); CVAR_BOOL (le_foliageCamera, false); CVAR_BOOL (le_foliageParallel, false); CVAR_BOOLF (le_foliageDrawBrushCoords, true, CVAR_SAVECONFIG); CVAR_BOOLF (le_foliageDrawInfo, true, CVAR_SAVECONFIG); UI_TRIGGER (FoliageMode); UI_TRIGGER (FoliageTexture); //============================================================================= /*==================== CFoliageTool::CFoliageTool( ====================*/ CFoliageTool::CFoliageTool() : ITool(TOOL_FOLIAGE, _T("foliage")), m_bWorking(false), m_bInverse(false), m_iX(0), m_iY(0), m_iXTile(0), m_iYTile(0), m_hLineMaterial(g_ResourceManager.Register(_T("/core/materials/line.material"), RES_MATERIAL)), m_bValidPosition(false), m_hFont(g_ResourceManager.LookUpName(_T("system_medium"), RES_FONTMAP)) { FoliageMode.Trigger(_T("auto")); } /*==================== CFoliageTool::PrimaryUp Left mouse button up action ====================*/ void CFoliageTool::PrimaryUp() { if (!m_bInverse) m_bWorking = false; } /*==================== CFoliageTool::PrimaryDown Default left mouse button down action ====================*/ void CFoliageTool::PrimaryDown() { m_bWorking = true; m_bInverse = false; CalcToolProperties(); } /*==================== CFoliageTool::SecondaryUp Right mouse button up action ====================*/ void CFoliageTool::SecondaryUp() { if (m_bInverse) m_bWorking = false; } /*==================== CFoliageTool::SecondaryDown Default right mouse button down action - not used in this case ====================*/ void CFoliageTool::SecondaryDown() { m_bWorking = true; m_bInverse = true; CalcToolProperties(); } /*==================== CFoliageTool::TertiaryUp Middle mouse button up action ====================*/ void CFoliageTool::TertiaryUp() { } /*==================== CFoliageTool::TertiaryDown Middle mouse button down action ====================*/ void CFoliageTool::TertiaryDown() { } /*==================== CFoliageTool::QuaternaryUp Scroll wheel up action ====================*/ void CFoliageTool::QuaternaryUp() { } /*==================== CFoliageTool::QuaternaryDown Scroll wheel down action ====================*/ void CFoliageTool::QuaternaryDown() { } /*==================== CFoliageTool::Cancel ====================*/ void CFoliageTool::Cancel() { } /*==================== CFoliageTool::Delete ====================*/ void CFoliageTool::Delete() { } /*==================== CFoliageTool::CalcToolProperties ====================*/ void CFoliageTool::CalcToolProperties() { STraceInfo trace; CBrush *pBrush = CBrush::GetCurrentBrush(); if (Editor.TraceCursor(trace, TRACE_TERRAIN) && pBrush) { // Clip against the brush data CRecti recBrush; pBrush->ClipBrush(recBrush); float fBrushCenterX((recBrush.left + recBrush.right) / 2.0f); float fBrushCenterY((recBrush.top + recBrush.bottom) / 2.0f); float fTestX((trace.v3EndPos.x - fBrushCenterX * Editor.GetWorld().GetScale()) / (Editor.GetWorld().GetScale())); float fTestY((trace.v3EndPos.y - fBrushCenterY * Editor.GetWorld().GetScale()) / (Editor.GetWorld().GetScale())); m_iX = fTestX < 0.0f ? INT_FLOOR(fTestX) : INT_CEIL(fTestX); m_iY = fTestY < 0.0f ? INT_FLOOR(fTestY) : INT_CEIL(fTestY); m_iXTile = INT_ROUND(fTestX); m_iYTile = INT_ROUND(fTestY); m_bValidPosition = true; m_v3EndPos = trace.v3EndPos; } else { m_bValidPosition = false; m_iX = 0; m_iY = 0; m_iXTile = 0; m_iYTile = 0; m_v3EndPos.Clear(); } /*if (Editor.TraceCursor(trace, TRACE_TERRAIN)) { m_iX = Editor.GetWorld().GetVertFromCoord(trace.v3EndPos.x); m_iY = Editor.GetWorld().GetVertFromCoord(trace.v3EndPos.y); m_iTileX = Editor.GetWorld().GetTileFromCoord(trace.v3EndPos.x); m_iTileY = Editor.GetWorld().GetTileFromCoord(trace.v3EndPos.y); m_v3EndPos = trace.v3EndPos; m_bValidPosition = true; } else { m_iX = -1; m_iY = -1; m_v3EndPos.Clear(); m_bValidPosition = false; }*/ if (m_bInverse) m_fAmount = le_foliageDensity2; else m_fAmount = le_foliageDensity; if (le_foliageTexture.IsModified()) { m_hTexture = g_ResourceManager.Register(le_foliageTexture, RES_TEXTURE); FoliageTexture.Trigger(le_foliageTexture); le_foliageTexture.SetModified(false); } } /*==================== CFoliageTool::AddFoliageDensity ====================*/ void CFoliageTool::AddFoliageDensity(SFoliageVertexEntry *pRegion, const CRecti &recArea, const CBrush &brush, float fDensity, float fStrength) { int iBrushSize(brush.GetBrushSize()); int iRegionIndex(0); for (int y(0); y < recArea.GetHeight(); ++y) { for (int x(0); x < recArea.GetWidth(); ++x) { float fDelta = brush[BRUSH_INDEX(x, y)] * fStrength; if (pRegion[iRegionIndex].fDensity > fDensity) { pRegion[iRegionIndex].fDensity -= fDelta; if(pRegion[iRegionIndex].fDensity < fDensity) pRegion[iRegionIndex].fDensity = fDensity; } else if (pRegion[iRegionIndex].fDensity < fDensity) { pRegion[iRegionIndex].fDensity += fDelta; if(pRegion[iRegionIndex].fDensity > fDensity) pRegion[iRegionIndex].fDensity = fDensity; } ++iRegionIndex; } } } /*==================== CFoliageTool::AddFoliageSize ====================*/ void CFoliageTool::AddFoliageSize(SFoliageVertexEntry *pRegion, const CRecti &recArea, const CBrush &brush, float fWidth, float fHeight, float fRandWidth, float fRandHeight, float fStrength) { int iBrushSize(brush.GetBrushSize()); int iRegionIndex(0); for (int y(0); y < recArea.GetHeight(); ++y) { for (int x(0); x < recArea.GetWidth(); ++x) { float fDelta = brush[BRUSH_INDEX(x, y)] * fStrength; // Width if (pRegion[iRegionIndex].v3Size.x > fWidth) { pRegion[iRegionIndex].v3Size.x -= fDelta; if(pRegion[iRegionIndex].v3Size.x < fWidth) pRegion[iRegionIndex].v3Size.x = fWidth; } else if (pRegion[iRegionIndex].v3Size.x < fWidth) { pRegion[iRegionIndex].v3Size.x += fDelta; if(pRegion[iRegionIndex].v3Size.x > fWidth) pRegion[iRegionIndex].v3Size.x = fWidth; } // Height if (pRegion[iRegionIndex].v3Size.y > fHeight) { pRegion[iRegionIndex].v3Size.y -= fDelta; if(pRegion[iRegionIndex].v3Size.y < fHeight) pRegion[iRegionIndex].v3Size.y = fHeight; } else if (pRegion[iRegionIndex].v3Size.y < fHeight) { pRegion[iRegionIndex].v3Size.y += fDelta; if(pRegion[iRegionIndex].v3Size.y > fHeight) pRegion[iRegionIndex].v3Size.y = fHeight; } // Width Jitter if (pRegion[iRegionIndex].v3Variance.x > fRandWidth) { pRegion[iRegionIndex].v3Variance.x -= fDelta; if(pRegion[iRegionIndex].v3Variance.x < fRandWidth) pRegion[iRegionIndex].v3Variance.x = fRandWidth; } else if (pRegion[iRegionIndex].v3Variance.x < fRandWidth) { pRegion[iRegionIndex].v3Variance.x += fDelta; if(pRegion[iRegionIndex].v3Variance.x > fRandWidth) pRegion[iRegionIndex].v3Variance.x = fRandWidth; } // Height Jitter if (pRegion[iRegionIndex].v3Variance.y > fRandHeight) { pRegion[iRegionIndex].v3Variance.y -= fDelta; if(pRegion[iRegionIndex].v3Variance.y < fRandHeight) pRegion[iRegionIndex].v3Variance.y = fRandHeight; } else if (pRegion[iRegionIndex].v3Variance.y < fRandHeight) { pRegion[iRegionIndex].v3Variance.y += fDelta; if(pRegion[iRegionIndex].v3Variance.y > fRandHeight) pRegion[iRegionIndex].v3Variance.y = fRandHeight; } ++iRegionIndex; } } } /*==================== CFoliageTool::AddFoliageScale ====================*/ void CFoliageTool::AddFoliageScale(SFoliageVertexEntry *pRegion, const CRecti &recArea, const CBrush &brush, float fFoliageScale, float fStrength) { int iBrushSize(brush.GetBrushSize()); int iRegionIndex(0); for (int y(0); y < recArea.GetHeight(); ++y) { for (int x(0); x < recArea.GetWidth(); ++x) { float fDelta(brush[BRUSH_INDEX(x, y)] * fStrength); if (pRegion[iRegionIndex].v3Size.z > fFoliageScale) { pRegion[iRegionIndex].v3Size.z -= fDelta; if(pRegion[iRegionIndex].v3Size.z < fFoliageScale) pRegion[iRegionIndex].v3Size.z = fFoliageScale; } else if (pRegion[iRegionIndex].v3Size.z < fFoliageScale) { pRegion[iRegionIndex].v3Size.z += fDelta; if(pRegion[iRegionIndex].v3Size.z > fFoliageScale) pRegion[iRegionIndex].v3Size.z = fFoliageScale; } ++iRegionIndex; } } } /*==================== CFoliageTool::FoliageSmooth ====================*/ void CFoliageTool::FoliageSmooth(SFoliageVertexEntry *pRegion, const CRecti &recArea, const CBrush &brush, float fStrength) { #define REGION_INDEX(x, y) ((x) + ((y) * recArea.GetWidth())) int iBrushSize(brush.GetBrushSize()); SFoliageVertexEntry *pRegionClean(K2_NEW_ARRAY(ctx_Editor, SFoliageVertexEntry, recArea.GetArea())); MemManager.Copy(pRegionClean, pRegion, sizeof(SFoliageVertexEntry) * recArea.GetArea()); for (int y(1); y < recArea.GetHeight() - 1; ++y) { for (int x(1); x < recArea.GetWidth() - 1; ++x) { float fLerp(brush[BRUSH_INDEX(x, y)] * fStrength); fLerp = CLAMP(fLerp, 0.0f, 1.0f); if (!fLerp) continue; CVec3f v3AverageSize = pRegionClean[REGION_INDEX(x - 1, y - 1)].v3Size + pRegionClean[REGION_INDEX(x, y - 1)].v3Size + pRegionClean[REGION_INDEX(x + 1, y - 1)].v3Size + pRegionClean[REGION_INDEX(x - 1, y)].v3Size + pRegionClean[REGION_INDEX(x, y)].v3Size + pRegionClean[REGION_INDEX(x + 1, y)].v3Size + pRegionClean[REGION_INDEX(x - 1, y + 1)].v3Size + pRegionClean[REGION_INDEX(x, y + 1)].v3Size + pRegionClean[REGION_INDEX(x + 1, y + 1)].v3Size; v3AverageSize /= 9.0f; pRegion[REGION_INDEX(x, y)].v3Size = LERP(fLerp, pRegion[REGION_INDEX(x, y)].v3Size, v3AverageSize); CVec3f v3AverageVariance = pRegionClean[REGION_INDEX(x - 1, y - 1)].v3Variance + pRegionClean[REGION_INDEX(x, y - 1)].v3Variance + pRegionClean[REGION_INDEX(x + 1, y - 1)].v3Variance + pRegionClean[REGION_INDEX(x - 1, y)].v3Variance + pRegionClean[REGION_INDEX(x, y)].v3Variance + pRegionClean[REGION_INDEX(x + 1, y)].v3Variance + pRegionClean[REGION_INDEX(x - 1, y + 1)].v3Variance + pRegionClean[REGION_INDEX(x, y + 1)].v3Variance + pRegionClean[REGION_INDEX(x + 1, y + 1)].v3Variance; v3AverageVariance /= 9.0f; pRegion[REGION_INDEX(x, y)].v3Variance = LERP(fLerp, pRegion[REGION_INDEX(x, y)].v3Variance, v3AverageVariance); float fDensity = pRegionClean[REGION_INDEX(x - 1, y - 1)].fDensity + pRegionClean[REGION_INDEX(x, y - 1)].fDensity + pRegionClean[REGION_INDEX(x + 1, y - 1)].fDensity + pRegionClean[REGION_INDEX(x - 1, y)].fDensity + pRegionClean[REGION_INDEX(x, y)].fDensity + pRegionClean[REGION_INDEX(x + 1, y)].fDensity + pRegionClean[REGION_INDEX(x - 1, y + 1)].fDensity + pRegionClean[REGION_INDEX(x, y + 1)].fDensity + pRegionClean[REGION_INDEX(x + 1, y + 1)].fDensity; fDensity /= 9.0f; pRegion[REGION_INDEX(x, y)].fDensity = LERP(fLerp, pRegion[REGION_INDEX(x, y)].fDensity, fDensity); } } K2_DELETE_ARRAY(pRegionClean); #undef REGION_INDEX } /*==================== CFoliageTool::FoliageAuto ====================*/ void CFoliageTool::FoliageAuto(SFoliageVertexEntry *pRegion, const CRecti &recArea, const CBrush &brush, float fDensity, float fWidth, float fHeight, float fRandWidth, float fRandHeight, float fScale, float fStrength) { int iBrushSize(brush.GetBrushSize()); int iRegionIndex(0); for (int y(0); y < recArea.GetHeight(); ++y) { for (int x(0); x < recArea.GetWidth(); ++x) { float fDelta = brush[BRUSH_INDEX(x, y)] * fStrength; // Density if (pRegion[iRegionIndex].fDensity > fDensity) { pRegion[iRegionIndex].fDensity -= fDelta; if(pRegion[iRegionIndex].fDensity < fDensity) pRegion[iRegionIndex].fDensity = fDensity; } else if (pRegion[iRegionIndex].fDensity < fDensity) { pRegion[iRegionIndex].fDensity += fDelta; if(pRegion[iRegionIndex].fDensity > fDensity) pRegion[iRegionIndex].fDensity = fDensity; } // Width if (pRegion[iRegionIndex].v3Size.x > fWidth) { pRegion[iRegionIndex].v3Size.x -= fDelta; if(pRegion[iRegionIndex].v3Size.x < fWidth) pRegion[iRegionIndex].v3Size.x = fWidth; } else if (pRegion[iRegionIndex].v3Size.x < fWidth) { pRegion[iRegionIndex].v3Size.x += fDelta; if(pRegion[iRegionIndex].v3Size.x > fWidth) pRegion[iRegionIndex].v3Size.x = fWidth; } // Height if (pRegion[iRegionIndex].v3Size.y > fHeight) { pRegion[iRegionIndex].v3Size.y -= fDelta; if(pRegion[iRegionIndex].v3Size.y < fHeight) pRegion[iRegionIndex].v3Size.y = fHeight; } else if (pRegion[iRegionIndex].v3Size.y < fHeight) { pRegion[iRegionIndex].v3Size.y += fDelta; if(pRegion[iRegionIndex].v3Size.y > fHeight) pRegion[iRegionIndex].v3Size.y = fHeight; } // Width Jitter if (pRegion[iRegionIndex].v3Variance.x > fRandWidth) { pRegion[iRegionIndex].v3Variance.x -= fDelta; if(pRegion[iRegionIndex].v3Variance.x < fRandWidth) pRegion[iRegionIndex].v3Variance.x = fRandWidth; } else if (pRegion[iRegionIndex].v3Variance.x < fRandWidth) { pRegion[iRegionIndex].v3Variance.x += fDelta; if(pRegion[iRegionIndex].v3Variance.x > fRandWidth) pRegion[iRegionIndex].v3Variance.x = fRandWidth; } // Height Jitter if (pRegion[iRegionIndex].v3Variance.y > fRandHeight) { pRegion[iRegionIndex].v3Variance.y -= fDelta; if(pRegion[iRegionIndex].v3Variance.y < fRandHeight) pRegion[iRegionIndex].v3Variance.y = fRandHeight; } else if (pRegion[iRegionIndex].v3Variance.y < fRandHeight) { pRegion[iRegionIndex].v3Variance.y += fDelta; if(pRegion[iRegionIndex].v3Variance.y > fRandHeight) pRegion[iRegionIndex].v3Variance.y = fRandHeight; } // Scale float fScaleDelta(fDelta / 16.0f); if (pRegion[iRegionIndex].v3Size.z > fScale) { pRegion[iRegionIndex].v3Size.z -= fScaleDelta; if(pRegion[iRegionIndex].v3Size.z < fScale) pRegion[iRegionIndex].v3Size.z = fScale; } else if (pRegion[iRegionIndex].v3Size.z < fScale) { pRegion[iRegionIndex].v3Size.z += fScaleDelta; if(pRegion[iRegionIndex].v3Size.z > fScale) pRegion[iRegionIndex].v3Size.z = fScale; } ++iRegionIndex; } } } /*==================== CFoliageTool::PaintFoliageVertex ====================*/ void CFoliageTool::PaintFoliageVertex(float fFrameTime) { SFoliageVertexEntry *pRegion(nullptr); try { CBrush *pBrush(CBrush::GetCurrentBrush()); if (pBrush == nullptr) EX_ERROR(_T("No brush selected")); //if (!Editor.GetWorld().IsInBounds(m_iX, m_iY, GRID_SPACE)) // EX_WARN(_T("Out of bounds coordinate")); // Clip against the brush data CRecti recClippedBrush; if (!pBrush->ClipBrush(recClippedBrush)) return; // Clip the brush against the world recClippedBrush.Shift(m_iX, m_iY); if (!Editor.GetWorld().ClipRect(recClippedBrush, GRID_SPACE)) return; // Get the region pRegion = K2_NEW_ARRAY(ctx_Editor, SFoliageVertexEntry, recClippedBrush.GetArea()); if (pRegion == nullptr) EX_ERROR(_T("Failed to allocate region")); if (!Editor.GetWorld().GetRegion(WORLD_VERT_FOLIAGE_MAP, recClippedBrush, pRegion, le_foliageLayer)) EX_ERROR(_T("Failed to retrieve region")); // Perform the operation recClippedBrush.Shift(-m_iX, -m_iY); float fScale(fFrameTime * le_foliageBrushStrength / 500.0f); switch (le_foliageMode) { case FOLIAGE_DENSITY: AddFoliageDensity(pRegion, recClippedBrush, *pBrush, m_bInverse ? le_foliageDensity2 : le_foliageDensity, fScale); break; case FOLIAGE_SIZE: AddFoliageSize(pRegion, recClippedBrush, *pBrush, m_bInverse ? le_foliageSizeWidth2 : le_foliageSizeWidth, m_bInverse ? le_foliageSizeHeight2 : le_foliageSizeHeight, m_bInverse ? le_foliageSizeRandWidth2 : le_foliageSizeRandWidth, m_bInverse ? le_foliageSizeRandHeight2 : le_foliageSizeRandHeight, fScale); break; case FOLIAGE_SCALE: AddFoliageScale(pRegion, recClippedBrush, *pBrush, m_bInverse ? le_foliageScale2 : le_foliageScale, fScale / 16.0f); break; case FOLIAGE_SMOOTH: FoliageSmooth(pRegion, recClippedBrush, *pBrush, fScale); break; case FOLIAGE_AUTO: FoliageAuto(pRegion, recClippedBrush, *pBrush, m_bInverse ? LERP(float(le_foliageAuto2), float(le_foliageDensity), float(le_foliageDensity2)) : LERP(float(le_foliageAuto), float(le_foliageDensity2), float(le_foliageDensity)), m_bInverse ? LERP(float(le_foliageAuto2), float(le_foliageSizeWidth), float(le_foliageSizeWidth2)) : LERP(float(le_foliageAuto), float(le_foliageSizeWidth2), float(le_foliageSizeWidth)), m_bInverse ? LERP(float(le_foliageAuto2), float(le_foliageSizeHeight), float(le_foliageSizeHeight2)) : LERP(float(le_foliageAuto), float(le_foliageSizeHeight2), float(le_foliageSizeHeight)), m_bInverse ? LERP(float(le_foliageAuto2), float(le_foliageSizeRandWidth), float(le_foliageSizeRandWidth2)) : LERP(float(le_foliageAuto), float(le_foliageSizeRandWidth2), float(le_foliageSizeRandWidth)), m_bInverse ? LERP(float(le_foliageAuto2), float(le_foliageSizeRandHeight), float(le_foliageSizeRandHeight2)) : LERP(float(le_foliageAuto), float(le_foliageSizeRandHeight2), float(le_foliageSizeRandHeight)), m_bInverse ? LERP(float(le_foliageAuto2), float(le_foliageScale), float(le_foliageScale2)) : LERP(float(le_foliageAuto), float(le_foliageScale2), float(le_foliageScale)), fScale); break; } // Apply the modified region recClippedBrush.Shift(m_iX, m_iY); if (!Editor.GetWorld().SetRegion(WORLD_VERT_FOLIAGE_MAP, recClippedBrush, pRegion, le_foliageLayer)) EX_ERROR(_T("SetRegion failed")); if (le_foliageMode == FOLIAGE_DENSITY) { for (int y(recClippedBrush.top); y < recClippedBrush.bottom; ++y) { for (int x(recClippedBrush.left); x < recClippedBrush.right; ++x) Vid.Notify(VID_NOTIFY_FOLIAGE_DENSITY_MODIFIED, x, y, 0, &Editor.GetWorld()); } } else { for (int y(recClippedBrush.top); y < recClippedBrush.bottom; ++y) { for (int x(recClippedBrush.left); x < recClippedBrush.right; ++x) Vid.Notify(VID_NOTIFY_FOLIAGE_SIZE_MODIFIED, x, y, 0, &Editor.GetWorld()); } } K2_DELETE_ARRAY(pRegion); } catch (CException &ex) { if (pRegion != nullptr) K2_DELETE_ARRAY(pRegion); ex.Process(_T("CFoliageTool::PaintFoliageVertex() - "), NO_THROW); } } /*==================== CFoliageTool::ApplyFoliageTexture ====================*/ void CFoliageTool::ApplyFoliageTexture(SFoliageTile *pRegion, const CRecti &recArea, const CBrush &brush, ResHandle hTexture, int iNumCrossQuads, byte yFlags) { int iBrushSize(brush.GetBrushSize()); int iRegionIndex(0); for (int y(0); y < recArea.GetHeight(); ++y) { for (int x(0); x < recArea.GetWidth(); ++x) { if (brush[BRUSH_INDEX(x, y)] > 0) { pRegion[iRegionIndex].iTextureRef = hTexture; pRegion[iRegionIndex].yNumCrossQuads = byte(iNumCrossQuads); pRegion[iRegionIndex].yFlags = yFlags; } ++iRegionIndex; } } } /*==================== CFoliageTool::ApplyFoliageTextureStroked Stroked to fix the alpha edge problems ====================*/ void CFoliageTool::ApplyFoliageTextureStroked(SFoliageTile *pRegion, const CRecti &recArea, const CBrush &brush, ResHandle hTexture, int iNumCrossQuads, byte yFlags) { int iBrushSize(brush.GetBrushSize()); int iRegionIndex(0); for (int y(0); y < recArea.GetHeight(); ++y) { for (int x(0); x < recArea.GetWidth(); ++x) { if (brush[BRUSH_INDEX(x, y)] > 0 || (recArea.left + x < iBrushSize - 1 && brush[BRUSH_INDEX(x + 1, y)] > 0) || (recArea.top + y < iBrushSize - 1 && brush[BRUSH_INDEX(x, y + 1)] > 0) || (recArea.left + x < iBrushSize - 1 && recArea.top + y < iBrushSize - 1 && brush[BRUSH_INDEX(x + 1, y + 1)] > 0)) { pRegion[iRegionIndex].iTextureRef = hTexture; pRegion[iRegionIndex].yNumCrossQuads = byte(iNumCrossQuads); pRegion[iRegionIndex].yFlags = yFlags; } ++iRegionIndex; } } } /*==================== CFoliageTool::PaintFoliageTile ====================*/ void CFoliageTool::PaintFoliageTile(float fFrameTime) { SFoliageTile *pRegion(nullptr); try { CBrush *pBrush(CBrush::GetCurrentBrush()); if (pBrush == nullptr) EX_ERROR(_T("No brush selected")); //if (!Editor.GetWorld().IsInBounds(m_iX, m_iY, TILE_SPACE)) // EX_WARN(_T("Out of bounds coordinate")); // Clip against the brush data CRecti recClippedBrush; if (!pBrush->ClipBrush(recClippedBrush)) return; int iX(m_iXTile); int iY(m_iYTile); if (le_foliageMode == FOLIAGE_AUTO) // Expand brush by one pixel in the negative direction to fix alpha edge problems { if (recClippedBrush.left > 0) { recClippedBrush.ShiftX(-1); recClippedBrush.StretchX(2); } if (recClippedBrush.top > 0) { recClippedBrush.ShiftY(-1); recClippedBrush.StretchY(2); } iX = m_iX; iY = m_iY; } // Clip the brush against the world recClippedBrush.Shift(iX, iY); if (!Editor.GetWorld().ClipRect(recClippedBrush, TILE_SPACE)) return; // Get the region pRegion = K2_NEW_ARRAY(ctx_Editor, SFoliageTile, recClippedBrush.GetArea()); if (pRegion == nullptr) EX_ERROR(_T("Failed to allocate region")); if (!Editor.GetWorld().GetRegion(WORLD_TILE_FOLIAGE_MAP, recClippedBrush, pRegion, le_foliageLayer)) EX_ERROR(_T("Failed to retrieve region")); // Perform the operation recClippedBrush.Shift(-iX, -iY); byte yFlags(0); if (le_foliageParallel) yFlags |= F_PARALLEL; else if (le_foliageCamera) yFlags |= F_CAMERA; if (le_foliageMode == FOLIAGE_AUTO) ApplyFoliageTextureStroked(pRegion, recClippedBrush, *pBrush, m_hTexture, le_foliageCrossQuads, yFlags); else ApplyFoliageTexture(pRegion, recClippedBrush, *pBrush, m_hTexture, le_foliageCrossQuads, yFlags); // Apply the modified region recClippedBrush.Shift(iX, iY); if (!Editor.GetWorld().SetRegion(WORLD_TILE_FOLIAGE_MAP, recClippedBrush, pRegion, le_foliageLayer)) EX_ERROR(_T("SetRegion failed")); for (int y(recClippedBrush.top); y < recClippedBrush.bottom; ++y) { for (int x(recClippedBrush.left); x < recClippedBrush.right; ++x) Vid.Notify(VID_NOTIFY_FOLIAGE_TEXTURE_MODIFIED, x, y, 0, &Editor.GetWorld()); } K2_DELETE_ARRAY(pRegion); } catch (CException &ex) { if (pRegion != nullptr) K2_DELETE_ARRAY(pRegion); ex.Process(_T("CFoliageTool::PaintFoliageTile() - "), NO_THROW); } } /*==================== CFoliageTool::Frame ====================*/ void CFoliageTool::Frame(float fFrameTime) { CalcToolProperties(); if (m_bWorking && m_bValidPosition) { switch (le_foliageMode) { case FOLIAGE_TEXTURE: PaintFoliageTile(fFrameTime); break; case FOLIAGE_DENSITY: case FOLIAGE_SIZE: case FOLIAGE_SCALE: case FOLIAGE_SMOOTH: PaintFoliageVertex(fFrameTime); break; case FOLIAGE_AUTO: PaintFoliageTile(fFrameTime); PaintFoliageVertex(fFrameTime); break; } } } /*==================== DrawInfoString ====================*/ static void DrawInfoString(const tstring &sString, int &iLine, CFontMap *pFontMap, ResHandle hFont) { float fWidth(pFontMap->GetStringWidth(sString)); Draw2D.SetColor(0.0f, 0.0f, 0.0f); Draw2D.String(Draw2D.GetScreenW() - fWidth - 3.0f, Draw2D.GetScreenH() - pFontMap->GetMaxHeight() * (iLine + 1) - 1.0f, fWidth, pFontMap->GetMaxHeight(), sString, hFont); Draw2D.SetColor(1.0f, 1.0f, 1.0f); Draw2D.String(Draw2D.GetScreenW() - fWidth - 4.0f, Draw2D.GetScreenH() - pFontMap->GetMaxHeight() * (iLine + 1) - 2.0f, fWidth, pFontMap->GetMaxHeight(), sString, hFont); ++iLine; } /*==================== CFoliageTool::Draw ====================*/ void CFoliageTool::Draw() { if (!m_bValidPosition) return; if (le_foliageDrawBrushCoords) { CFontMap *pFontMap(g_ResourceManager.GetFontMap(m_hFont)); Draw2D.SetColor(0.0f, 0.0f, 0.0f); Draw2D.String(4.0f, Draw2D.GetScreenH() - pFontMap->GetMaxHeight() - 1.0f, Draw2D.GetScreenW(), pFontMap->GetMaxHeight(), XtoA(m_v3EndPos), m_hFont); Draw2D.SetColor(1.0f, 1.0f, 1.0f); Draw2D.String(3.0f, Draw2D.GetScreenH() - pFontMap->GetMaxHeight() - 2.0f, Draw2D.GetScreenW(), pFontMap->GetMaxHeight(), XtoA(m_v3EndPos), m_hFont); } if (le_foliageDrawInfo) { CFontMap *pFontMap(g_ResourceManager.GetFontMap(m_hFont)); CWorld &oWorld(Editor.GetWorld()); const float fTileSize(float(oWorld.GetScale())); int iTileX(oWorld.GetTileFromCoord(m_v3EndPos.x - Editor.GetWorld().GetScale())); int iTileY(oWorld.GetTileFromCoord(m_v3EndPos.y - Editor.GetWorld().GetScale())); float fLerps[2] = { FRAC(m_v3EndPos.x / fTileSize), FRAC(m_v3EndPos.y / fTileSize) }; int iLine(0); // // Size, Rand Size, Scale // CVec3f v3Sizes[4] = { oWorld.GetFoliageSize(iTileX, iTileY, le_foliageLayer), oWorld.GetFoliageSize(iTileX + 1, iTileY, le_foliageLayer), oWorld.GetFoliageSize(iTileX, iTileY + 1, le_foliageLayer), oWorld.GetFoliageSize(iTileX + 1, iTileY + 1, le_foliageLayer) }; CVec3f v3Variances[4] = { oWorld.GetFoliageVariance(iTileX, iTileY, le_foliageLayer), oWorld.GetFoliageVariance(iTileX + 1, iTileY, le_foliageLayer), oWorld.GetFoliageVariance(iTileX, iTileY + 1, le_foliageLayer), oWorld.GetFoliageVariance(iTileX + 1, iTileY + 1, le_foliageLayer) }; float fWidths[4] = { v3Sizes[0].x, v3Sizes[1].x, v3Sizes[2].x, v3Sizes[3].x }; float fPCFWidth(PCF(fLerps, fWidths)); float fHeights[4] = { v3Sizes[0].y, v3Sizes[1].y, v3Sizes[2].y, v3Sizes[3].y }; float fPCFHeight(PCF(fLerps, fHeights)); float fRandWidths[4] = { v3Variances[0].x, v3Variances[1].x, v3Variances[2].x, v3Variances[3].x }; float fPCFRandWidth(PCF(fLerps, fRandWidths)); float fRandHeights[4] = { v3Variances[0].y, v3Variances[1].y, v3Variances[2].y, v3Variances[3].y }; float fPCFRandHeight(PCF(fLerps, fRandHeights)); float fScales[4] = { v3Sizes[0].z, v3Sizes[1].z, v3Sizes[2].z, v3Sizes[3].z }; float fPCFScale(PCF(fLerps, fScales)); DrawInfoString(_T("Rand Size: ") + XtoA(fPCFRandWidth, 0, 0, 1) + _T(", ") + XtoA(fPCFRandHeight, 0, 0, 1), iLine, pFontMap, m_hFont); DrawInfoString(_T("Size: ") + XtoA(fPCFWidth, 0, 0, 1) + _T(", ") + XtoA(fPCFHeight, 0, 0, 1), iLine, pFontMap, m_hFont); DrawInfoString(_T("Scale: ") + XtoA(fPCFScale, 0, 0, 1), iLine, pFontMap, m_hFont); // // Density // float fDensity[4] = { oWorld.GetFoliageDensity(iTileX, iTileY, le_foliageLayer), oWorld.GetFoliageDensity(iTileX + 1, iTileY, le_foliageLayer), oWorld.GetFoliageDensity(iTileX, iTileY + 1, le_foliageLayer), oWorld.GetFoliageDensity(iTileX + 1, iTileY + 1, le_foliageLayer) }; float fPCFDensity(PCF(fLerps, fDensity)); DrawInfoString(_T("Density: ") + XtoA(fPCFDensity, 0, 0, 1), iLine, pFontMap, m_hFont); DrawInfoString(_T("CrossQuads: ") + XtoA(oWorld.GetFoliageCrossQuads(iTileX, iTileY, le_foliageLayer)), iLine, pFontMap, m_hFont); DrawInfoString(_T("Material: ") + Filename_StripPath(g_ResourceManager.GetPath(oWorld.GetFoliageMaterial(iTileX, iTileY, le_foliageLayer))), iLine, pFontMap, m_hFont); DrawInfoString(_T("Texture: ") + Filename_StripPath(g_ResourceManager.GetPath(oWorld.GetFoliageTexture(iTileX, iTileY, le_foliageLayer))), iLine, pFontMap, m_hFont); DrawInfoString(_T("Layer ") + XtoA(le_foliageLayer + 1), iLine, pFontMap, m_hFont); } } /*==================== CFoliageTool::Render ====================*/ void CFoliageTool::Render() { if (!le_foliageDrawBrushInfluence || !m_bValidPosition) return; SSceneFaceVert poly[1024]; MemManager.Set(poly, 0, sizeof(poly)); int p = 0; if (le_foliageMode != FOLIAGE_TEXTURE) { CBrush *pBrush = CBrush::GetCurrentBrush(); float fTileSize = Editor.GetWorld().GetScale(); if (!pBrush) return; int iX = m_iX, iY = m_iY; for (int y = 0; y < pBrush->GetBrushSize() - 1; ++y) { for (int x = 0; x < pBrush->GetBrushSize() - 1; ++x) { if (p >= 1024) // restart batch if we overflow { SceneManager.AddPoly(p, poly, m_hLineMaterial, POLY_LINELIST | POLY_NO_DEPTH_TEST); MemManager.Set(poly, 0, sizeof(poly)); p = 0; } int i = x + y * pBrush->GetBrushSize(); int dX = iX + x; int dY = iY + y; if (!Editor.GetWorld().IsInBounds(dX, dY, GRID_SPACE)) continue; // left if (dY < Editor.GetWorld().GetGridHeight() - 1) { byte alpha0 = CLAMP(INT_FLOOR((*pBrush)[i] * le_foliageBrushInfluenceAlpha), 0, 255); byte alpha1 = CLAMP(INT_FLOOR((*pBrush)[i + pBrush->GetBrushSize()] * le_foliageBrushInfluenceAlpha), 0, 255); if (alpha0 || alpha1) { poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, dY); SET_VEC4(poly[p].col, 0, 255, 0, alpha0); ++p; poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = (dY + 1) * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, (dY + 1)); SET_VEC4(poly[p].col, 0, 255, 0, alpha1); ++p; } } if (p >= 1024) // restart batch if we overflow { SceneManager.AddPoly(p, poly, m_hLineMaterial, POLY_LINELIST | POLY_NO_DEPTH_TEST); MemManager.Set(poly, 0, sizeof(poly)); p = 0; } // top if (dX < Editor.GetWorld().GetGridWidth() - 1) { byte alpha0 = INT_FLOOR((*pBrush)[i] * le_foliageBrushInfluenceAlpha); byte alpha1 = INT_FLOOR((*pBrush)[i + 1] * le_foliageBrushInfluenceAlpha); if (alpha0 || alpha1) { poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, dY); SET_VEC4(poly[p].col, 0, 255, 0, alpha0); ++p; poly[p].vtx[0] = (dX + 1) * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint((dX + 1), dY); SET_VEC4(poly[p].col, 0, 255, 0, alpha1); ++p; } } } } if (p > 0) SceneManager.AddPoly(p, poly, m_hLineMaterial, POLY_LINELIST | POLY_NO_DEPTH_TEST); p = 0; } else { CBrush *pBrush = CBrush::GetCurrentBrush(); float fTileSize = Editor.GetWorld().GetScale(); if (!pBrush) return; int iX = m_iXTile, iY = m_iYTile; for (int y = 0; y < pBrush->GetBrushSize(); ++y) { for (int x = 0; x < pBrush->GetBrushSize(); ++x) { int i = x + y * pBrush->GetBrushSize(); // left if ((x > 0 && (*pBrush)[i] && !(*pBrush)[i - 1]) || (x == 0 && (*pBrush)[i])) { int dX = iX + x; int dY = iY + y; if (Editor.GetWorld().IsInBounds(dX, dY, GRID_SPACE) && Editor.GetWorld().IsInBounds(dX, dY + 1, GRID_SPACE)) { poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, dY); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = (dY + 1) * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, (dY + 1)); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; } } // right if ((x < pBrush->GetBrushSize() - 1 && (*pBrush)[i] && !(*pBrush)[i + 1]) || (x == pBrush->GetBrushSize() - 1 && (*pBrush)[i])) { int dX = iX + x; int dY = iY + y; if (Editor.GetWorld().IsInBounds(dX + 1, dY, GRID_SPACE) && Editor.GetWorld().IsInBounds(dX + 1, dY + 1, GRID_SPACE)) { poly[p].vtx[0] = (dX + 1) * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint((dX + 1), dY); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; poly[p].vtx[0] = (dX + 1) * fTileSize; poly[p].vtx[1] = (dY + 1) * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint((dX + 1), (dY+ 1)); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; } } // top if ((y > 0 && (*pBrush)[i] && !(*pBrush)[i - pBrush->GetBrushSize()]) || (y == 0 && (*pBrush)[i])) { int dX = iX + x; int dY = iY + y; if (Editor.GetWorld().IsInBounds(dX, dY, GRID_SPACE) && Editor.GetWorld().IsInBounds(dX + 1, dY, GRID_SPACE)) { poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, dY); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; poly[p].vtx[0] = (dX + 1) * fTileSize; poly[p].vtx[1] = dY * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint((dX + 1), dY); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; } } // bottom if ((y < pBrush->GetBrushSize() - 1 && (*pBrush)[i] && !(*pBrush)[i+pBrush->GetBrushSize()]) || (y == pBrush->GetBrushSize() - 1 && (*pBrush)[i])) { int dX = iX + x; int dY = iY + y; if (Editor.GetWorld().IsInBounds(dX + 1, dY + 1, GRID_SPACE) && Editor.GetWorld().IsInBounds(dX, dY + 1, GRID_SPACE)) { poly[p].vtx[0] = (dX + 1) * fTileSize; poly[p].vtx[1] = (dY + 1) * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint((dX + 1), (dY+ 1)); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; poly[p].vtx[0] = dX * fTileSize; poly[p].vtx[1] = (dY + 1) * fTileSize; poly[p].vtx[2] = Editor.GetWorld().GetGridPoint(dX, (dY + 1)); SET_VEC4(poly[p].col, 255, 255, 255, 255); ++p; } } } } if (p > 0) SceneManager.AddPoly(p, poly, m_hLineMaterial, POLY_LINELIST | POLY_NO_DEPTH_TEST); p = 0; } } /*-------------------- cmdFoliageMode --------------------*/ UI_VOID_CMD(FoliageMode, 1) { if (vArgList.size() < 1) { Console << _T("syntax: foliagemode texture|density|size|scale|smooth|auto") << newl; return; } tstring sValue(vArgList[0]->Evaluate()); if (sValue == _T("texture")) { le_foliageMode = FOLIAGE_TEXTURE; FoliageMode.Trigger(_T("Texture")); return; } else if (sValue == _T("density")) { le_foliageMode = FOLIAGE_DENSITY; FoliageMode.Trigger(_T("Density")); return; } else if (sValue == _T("size")) { le_foliageMode = FOLIAGE_SIZE; FoliageMode.Trigger(_T("Size")); return; } else if (sValue == _T("scale")) { le_foliageMode = FOLIAGE_SCALE; FoliageMode.Trigger(_T("Scale")); return; } else if (sValue == _T("smooth")) { le_foliageMode = FOLIAGE_SMOOTH; FoliageMode.Trigger(_T("Smooth")); return; } else if (sValue == _T("auto")) { le_foliageMode = FOLIAGE_AUTO; FoliageMode.Trigger(_T("auto")); return; } }
0
0.96917
1
0.96917
game-dev
MEDIA
0.69454
game-dev,graphics-rendering
0.957507
1
0.957507
kvakvs/hge
1,392
src/helpers/hgevector.cpp
/*----------------------------------------------------------------------------- * Haaf's Game Engine 1.9 * Copyright (C) 2003-2007, Relish Games * Maintained 2012-2021 by dmytro.lytovchenko@gmail.com (github @kvakvs) * Github -- https://github.com/kvakvs/hge | Discord -- https://discord.gg/TdjamHt * * Old website: http://hge.relishgames.com; Old forum: http://relishgames.com/forum *-----------------------------------------------------------------------------*/ // // hgeVector helper class implementation // #include <hgevector.h> float hgeVector::InvSqrt(const float x) { union { int int_part; float float_part; } convertor{}; convertor.float_part = x; convertor.int_part = 0x5f3759df - (convertor.int_part >> 1); return convertor.float_part * (1.5f - 0.4999f * x * convertor.float_part * convertor.float_part); } /* hgeVector *hgeVector::Normalize() { float lenRcp; lenRcp=sqrtf(Dot(this)); if(lenRcp) { lenRcp=1.0f/lenRcp; x*=lenRcp; y*=lenRcp; } return this; } */ float hgeVector::Angle(const hgeVector *v) const { if (v) { hgeVector s = *this, t = *v; s.Normalize(); t.Normalize(); return acosf(s.Dot(&t)); } return atan2f(y, x); } hgeVector *hgeVector::Rotate(float a) { hgeVector v; v.x = x * cosf(a) - y * sinf(a); v.y = x * sinf(a) + y * cosf(a); x = v.x; y = v.y; return this; }
0
0.688021
1
0.688021
game-dev
MEDIA
0.751458
game-dev
0.884269
1
0.884269
Citadel-Station-13/Citadel-Station-13
2,633
code/game/objects/effects/alien_acid.dm
/obj/effect/acid gender = PLURAL name = "acid" desc = "Burbling corrosive stuff." icon_state = "acid" density = FALSE opacity = 0 anchored = TRUE resistance_flags = FIRE_PROOF | UNACIDABLE | ACID_PROOF layer = ABOVE_NORMAL_TURF_LAYER var/turf/target var/acid_level = 0 // Removed from obj, so it goes here now /obj/effect/acid/Initialize(mapload, acid_pwr, acid_amt) . = ..() target = get_turf(src) if(acid_amt) acid_level = min( (clamp(round(acid_amt, 1), 0, INFINITY)) *acid_pwr, 12000) //capped so the acid effect doesn't last a half hour on the floor. //handle APCs and newscasters and stuff nicely pixel_x = target.pixel_x + rand(-4,4) pixel_y = target.pixel_y + rand(-4,4) START_PROCESSING(SSobj, src) /obj/effect/acid/Destroy() STOP_PROCESSING(SSobj, src) target = null return ..() /obj/effect/acid/process() . = 1 if(!target) qdel(src) return FALSE if(prob(5)) playsound(loc, 'sound/items/welder.ogg', 100, 1) for(var/obj/O in target) if(prob(20) && !(resistance_flags & UNACIDABLE)) if(O.acid_level() < acid_level*0.3) var/acid_used = min(acid_level*0.05, 20) O.acid_act(10, acid_used) acid_level = max(0, acid_level - acid_used*10) acid_level = max(acid_level - (5 + 2*round(sqrt(acid_level))), 0) if(acid_level <= 0) qdel(src) return FALSE /obj/effect/acid/Crossed(AM as mob|obj) . = ..() if(isliving(AM)) var/mob/living/L = AM if(L.movement_type & FLYING) return if(L.m_intent != MOVE_INTENT_WALK && prob(40)) var/acid_used = min(acid_level*0.05, 20) if(L.acid_act(10, acid_used, "feet")) acid_level = max(0, acid_level - acid_used*10) playsound(L, 'sound/weapons/sear.ogg', 50, 1) to_chat(L, "<span class='userdanger'>[src] burns you!</span>") //xenomorph corrosive acid /obj/effect/acid/alien var/target_strength = 30 /obj/effect/acid/alien/process() . = ..() if(.) if(prob(45)) playsound(loc, 'sound/items/welder.ogg', 100, 1) target_strength-- if(target_strength <= 0) target.visible_message("<span class='warning'>[target] collapses under its own weight into a puddle of goop and undigested debris!</span>") target.acid_melt() qdel(src) else switch(target_strength) if(24) visible_message("<span class='warning'>[target] is holding up against the acid!</span>") if(16) visible_message("<span class='warning'>[target] is being melted by the acid!</span>") if(8) visible_message("<span class='warning'>[target] is struggling to withstand the acid!</span>") if(4) visible_message("<span class='warning'>[target] begins to crumble under the acid!</span>")
0
0.830988
1
0.830988
game-dev
MEDIA
0.994396
game-dev
0.844921
1
0.844921
Mirsario/TerrariaOverhaul
4,227
Utilities/Xna/MathUtils.cs
// Copyright (c) 2020-2025 Mirsario & Contributors. // Released under the GNU General Public License 3.0. // See LICENSE.md for details. using System; using Microsoft.Xna.Framework; namespace TerrariaOverhaul.Utilities.Xna; internal static class MathUtils { public static float Modulo(float value, float length) => value - (float)Math.Floor(value / length) * length; public static double Modulo(double value, double length) => value - (float)Math.Floor(value / length) * length; public static int Modulo(int value, int length) { int r = value % length; return r < 0 ? r + length : r; } public static int Clamp(int value, int min, int max) => value <= min ? min : value >= max ? max : value; public static float Clamp(float value, float min, float max) => value <= min ? min : value >= max ? max : value; public static double Clamp(double value, double min, double max) => value <= min ? min : value >= max ? max : value; public static float Clamp01(float value) => value <= 0f ? 0f : value >= 1f ? 1f : value; public static double Clamp01(double value) => value <= 0.0 ? 0.0 : value >= 1.0 ? 1.0 : value; public static int MaxAbs(int a, int b) => Math.Abs(a) >= Math.Abs(b) ? a : b; public static float MaxAbs(float a, float b) => Math.Abs(a) >= Math.Abs(b) ? a : b; public static int MinAbs(int a, int b) => Math.Abs(a) <= Math.Abs(b) ? a : b; public static float MinAbs(float a, float b) => Math.Abs(a) <= Math.Abs(b) ? a : b; public static float Lerp(float value1, float value2, float amount) => value1 + (value2 - value1) * amount; public static double Lerp(double value1, double value2, double amount) => value1 + (value2 - value1) * amount; public static float InverseLerp(float value, float start, float end) => (value - start) / (end - start); public static double InverseLerp(double value, double start, double end) => (value - start) / (end - start); public static float LerpRadians(float a, float b, float factor) { float result; float diff = b - a; if (diff < -MathHelper.Pi) { // Lerp upwards past TwoPi b += MathHelper.TwoPi; result = Lerp(a, b, factor); if (result >= MathHelper.TwoPi) { result -= MathHelper.TwoPi; } } else if (diff > MathHelper.Pi) { // Lerp downwards past 0 b -= MathHelper.TwoPi; result = Lerp(a, b, factor); if (result < 0f) { result += MathHelper.TwoPi; } } else { // Straight lerp result = Lerp(a, b, factor); } return result; } public static float RadiansToPitch(float radians) { radians = Modulo(radians, MathHelper.TwoPi); if (radians < MathHelper.PiOver2) { return 0.5f - radians / MathHelper.Pi; // [0.5 - 1.0] } else if (radians < MathHelper.Pi * 1.5f) { return (radians - MathHelper.PiOver2) / MathHelper.Pi; // [0.0 - 1.0] } else { return 1f - (radians - MathHelper.Pi * 1.5f) / MathHelper.Pi; // [0.0 - 0.5] } } public static float DegreesToPitch(float degrees) { degrees = Modulo(degrees, 360f); if (degrees < 90f) { return 0.5f - degrees / 180f; // [0.5 - 1.0] } else if (degrees < 270f) { return (degrees - 90f) / 180f; // [0.0 - 1.0] } else { return 1f - (degrees - 270f) / 180f; // [0.0 - 0.5] } } public static float StepTowards(float value, float goal, float step) { if (goal > value) { value += step; if (value > goal) { return goal; } } else if (goal < value) { value -= step; if (value < goal) { return goal; } } return value; } public static float DistancePower(float distance, float maxDistance) { if (distance > maxDistance) return 0f; if (distance <= 0f) return 1f; float result = 1f - distance / maxDistance; return float.IsNaN(result) ? 0f : result; } public static float Damp(float source, float destination, float smoothing, float dt) { // See this: // https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp return Lerp(source, destination, 1f - MathF.Pow(smoothing, dt)); } public static Vector2 Damp(Vector2 source, Vector2 destination, float smoothing, float dt) { return new( Damp(source.X, destination.X, smoothing, dt), Damp(source.Y, destination.Y, smoothing, dt) ); } }
0
0.87145
1
0.87145
game-dev
MEDIA
0.68065
game-dev
0.982664
1
0.982664
thefirefox12537/qctools_tff
8,987
Python/Tools/demo/life.py
#!/usr/bin/env python3 """ A curses-based version of Conway's Game of Life. An empty board will be displayed, and the following commands are available: E : Erase the board R : Fill the board randomly S : Step for a single generation C : Update continuously until a key is struck Q : Quit Cursor keys : Move the cursor around the board Space or Enter : Toggle the contents of the cursor's position Contributed by Andrew Kuchling, Mouse support and color by Dafydd Crosby. """ import curses import random class LifeBoard: """Encapsulates a Life board Attributes: X,Y : horizontal and vertical size of the board state : dictionary mapping (x,y) to 0 or 1 Methods: display(update_board) -- If update_board is true, compute the next generation. Then display the state of the board and refresh the screen. erase() -- clear the entire board make_random() -- fill the board randomly set(y,x) -- set the given cell to Live; doesn't refresh the screen toggle(y,x) -- change the given cell from live to dead, or vice versa, and refresh the screen display """ def __init__(self, scr, char=ord('*')): """Create a new LifeBoard instance. scr -- curses screen object to use for display char -- character used to render live cells (default: '*') """ self.state = {} self.scr = scr Y, X = self.scr.getmaxyx() self.X, self.Y = X - 2, Y - 2 - 1 self.char = char self.scr.clear() # Draw a border around the board border_line = '+' + (self.X * '-') + '+' self.scr.addstr(0, 0, border_line) self.scr.addstr(self.Y + 1, 0, border_line) for y in range(0, self.Y): self.scr.addstr(1 + y, 0, '|') self.scr.addstr(1 + y, self.X + 1, '|') self.scr.refresh() def set(self, y, x): """Set a cell to the live state""" if x < 0 or self.X <= x or y < 0 or self.Y <= y: raise ValueError("Coordinates out of range %i,%i" % (y, x)) self.state[x, y] = 1 def toggle(self, y, x): """Toggle a cell's state between live and dead""" if x < 0 or self.X <= x or y < 0 or self.Y <= y: raise ValueError("Coordinates out of range %i,%i" % (y, x)) if (x, y) in self.state: del self.state[x, y] self.scr.addch(y + 1, x + 1, ' ') else: self.state[x, y] = 1 if curses.has_colors(): # Let's pick a random color! self.scr.attrset(curses.color_pair(random.randrange(1, 7))) self.scr.addch(y + 1, x + 1, self.char) self.scr.attrset(0) self.scr.refresh() def erase(self): """Clear the entire board and update the board display""" self.state = {} self.display(update_board=False) def display(self, update_board=True): """Display the whole board, optionally computing one generation""" M, N = self.X, self.Y if not update_board: for i in range(0, M): for j in range(0, N): if (i, j) in self.state: self.scr.addch(j + 1, i + 1, self.char) else: self.scr.addch(j + 1, i + 1, ' ') self.scr.refresh() return d = {} self.boring = 1 for i in range(0, M): L = range(max(0, i - 1), min(M, i + 2)) for j in range(0, N): s = 0 live = (i, j) in self.state for k in range(max(0, j - 1), min(N, j + 2)): for l in L: if (l, k) in self.state: s += 1 s -= live if s == 3: # Birth d[i, j] = 1 if curses.has_colors(): # Let's pick a random color! self.scr.attrset(curses.color_pair( random.randrange(1, 7))) self.scr.addch(j + 1, i + 1, self.char) self.scr.attrset(0) if not live: self.boring = 0 elif s == 2 and live: # Survival d[i, j] = 1 elif live: # Death self.scr.addch(j + 1, i + 1, ' ') self.boring = 0 self.state = d self.scr.refresh() def make_random(self): "Fill the board with a random pattern" self.state = {} for i in range(0, self.X): for j in range(0, self.Y): if random.random() > 0.5: self.set(j, i) def erase_menu(stdscr, menu_y): "Clear the space where the menu resides" stdscr.move(menu_y, 0) stdscr.clrtoeol() stdscr.move(menu_y + 1, 0) stdscr.clrtoeol() def display_menu(stdscr, menu_y): "Display the menu of possible keystroke commands" erase_menu(stdscr, menu_y) # If color, then light the menu up :-) if curses.has_colors(): stdscr.attrset(curses.color_pair(1)) stdscr.addstr(menu_y, 4, 'Use the cursor keys to move, and space or Enter to toggle a cell.') stdscr.addstr(menu_y + 1, 4, 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit') stdscr.attrset(0) def keyloop(stdscr): # Clear the screen and display the menu of keys stdscr.clear() stdscr_y, stdscr_x = stdscr.getmaxyx() menu_y = (stdscr_y - 3) - 1 display_menu(stdscr, menu_y) # If color, then initialize the color pairs if curses.has_colors(): curses.init_pair(1, curses.COLOR_BLUE, 0) curses.init_pair(2, curses.COLOR_CYAN, 0) curses.init_pair(3, curses.COLOR_GREEN, 0) curses.init_pair(4, curses.COLOR_MAGENTA, 0) curses.init_pair(5, curses.COLOR_RED, 0) curses.init_pair(6, curses.COLOR_YELLOW, 0) curses.init_pair(7, curses.COLOR_WHITE, 0) # Set up the mask to listen for mouse events curses.mousemask(curses.BUTTON1_CLICKED) # Allocate a subwindow for the Life board and create the board object subwin = stdscr.subwin(stdscr_y - 3, stdscr_x, 0, 0) board = LifeBoard(subwin, char=ord('*')) board.display(update_board=False) # xpos, ypos are the cursor's position xpos, ypos = board.X // 2, board.Y // 2 # Main loop: while True: stdscr.move(1 + ypos, 1 + xpos) # Move the cursor c = stdscr.getch() # Get a keystroke if 0 < c < 256: c = chr(c) if c in ' \n': board.toggle(ypos, xpos) elif c in 'Cc': erase_menu(stdscr, menu_y) stdscr.addstr(menu_y, 6, ' Hit any key to stop continuously ' 'updating the screen.') stdscr.refresh() # Activate nodelay mode; getch() will return -1 # if no keystroke is available, instead of waiting. stdscr.nodelay(1) while True: c = stdscr.getch() if c != -1: break stdscr.addstr(0, 0, '/') stdscr.refresh() board.display() stdscr.addstr(0, 0, '+') stdscr.refresh() stdscr.nodelay(0) # Disable nodelay mode display_menu(stdscr, menu_y) elif c in 'Ee': board.erase() elif c in 'Qq': break elif c in 'Rr': board.make_random() board.display(update_board=False) elif c in 'Ss': board.display() else: # Ignore incorrect keys pass elif c == curses.KEY_UP and ypos > 0: ypos -= 1 elif c == curses.KEY_DOWN and ypos + 1 < board.Y: ypos += 1 elif c == curses.KEY_LEFT and xpos > 0: xpos -= 1 elif c == curses.KEY_RIGHT and xpos + 1 < board.X: xpos += 1 elif c == curses.KEY_MOUSE: mouse_id, mouse_x, mouse_y, mouse_z, button_state = curses.getmouse() if (mouse_x > 0 and mouse_x < board.X + 1 and mouse_y > 0 and mouse_y < board.Y + 1): xpos = mouse_x - 1 ypos = mouse_y - 1 board.toggle(ypos, xpos) else: # They've clicked outside the board curses.flash() else: # Ignore incorrect keys pass def main(stdscr): keyloop(stdscr) # Enter the main loop if __name__ == '__main__': curses.wrapper(main)
0
0.830234
1
0.830234
game-dev
MEDIA
0.467332
game-dev
0.909457
1
0.909457
Slushi-Github/Slushi-Engine
6,800
funkinscsource/backend/WeekData.hx
package backend; import lime.utils.Assets; import openfl.utils.Assets as OpenFlAssets; typedef WeekFile = { // JSON variables var songs:Array<Dynamic>; var weekCharacters:Array<String>; var weekBackground:String; var weekBefore:String; var storyName:String; var weekName:String; var freeplayColor:Array<Int>; var startUnlocked:Bool; var hiddenUntilUnlocked:Bool; var hideStoryMode:Bool; var hideFreeplay:Bool; var difficulties:String; var defaultDifficulty:String; var blockOpponentMode:Null<Bool>; } class WeekData { public static var weeksLoaded:Map<String, WeekData> = new Map<String, WeekData>(); public static var weeksList:Array<String> = []; public var folder:String = ''; // JSON variables public var songs:Array<Dynamic>; public var weekCharacters:Array<String>; public var weekBackground:String; public var weekBefore:String; public var storyName:String; public var weekName:String; public var freeplayColor:Array<Int>; public var startUnlocked:Bool; public var hiddenUntilUnlocked:Bool; public var hideStoryMode:Bool; public var hideFreeplay:Bool; public var difficulties:String; public var defaultDifficulty:String; public var blockOpponentMode:Null<Bool>; public var fileName:String; public static function createWeekFile():WeekFile { var weekFile:WeekFile = { songs: [ ["Bopeebo", "dad", [146, 113, 253], false], ["Fresh", "dad", [146, 113, 253], false], ["Dad Battle", "dad", [146, 113, 253], false] ], #if BASE_GAME_FILES weekCharacters: ['dad', 'bf', 'gf'], #else weekCharacters: ['bf', 'bf', 'gf'], #end weekBackground: 'mainStage', weekBefore: 'tutorial', storyName: 'Your New Week', weekName: 'Custom Week', freeplayColor: [146, 113, 253], startUnlocked: true, hiddenUntilUnlocked: false, hideStoryMode: false, hideFreeplay: false, difficulties: '', defaultDifficulty: '', blockOpponentMode: null }; return weekFile; } // HELP: Is there any way to convert a WeekFile to WeekData without having to put all variables there manually? I'm kind of a noob in haxe lmao public function new(weekFile:WeekFile, fileName:String) { // here ya go - MiguelItsOut for (field in Reflect.fields(weekFile)) if (Reflect.fields(this).contains(field)) // Reflect.hasField() won't fucking work :/ Reflect.setProperty(this, field, Reflect.getProperty(weekFile, field)); this.fileName = fileName; } public static function reloadWeekFiles(isStoryMode:Null<Bool> = false) { weeksList = []; weeksLoaded.clear(); #if MODS_ALLOWED var directories:Array<String> = [Paths.mods(), Paths.getSharedPath()]; var originalLength:Int = directories.length; for (mod in Mods.parseList().enabled) directories.push(Paths.mods(mod + '/')); #else var directories:Array<String> = [Paths.getSharedPath()]; var originalLength:Int = directories.length; #end var sexList:Array<String> = CoolUtil.coolTextFile(Paths.getSharedPath('data/weeks/weekList.txt')); for (i in 0...sexList.length) { for (j in 0...directories.length) { var fileToCheck:String = directories[j] + 'data/weeks/' + sexList[i] + '.json'; if (!weeksLoaded.exists(sexList[i])) { var week:WeekFile = getWeekFile(fileToCheck); if (week != null) { var weekFile:WeekData = new WeekData(week, sexList[i]); #if MODS_ALLOWED if (j >= originalLength) { weekFile.folder = directories[j].substring(Paths.mods().length, directories[j].length - 1); } #end if (weekFile != null && (isStoryMode == null || (isStoryMode && !weekFile.hideStoryMode) || (!isStoryMode && !weekFile.hideFreeplay))) { weeksLoaded.set(sexList[i], weekFile); weeksList.push(sexList[i]); } } } } } #if MODS_ALLOWED for (i in 0...directories.length) { var directory:String = directories[i] + 'data/weeks/'; if (FileSystem.exists(directory)) { var listOfWeeks:Array<String> = CoolUtil.coolTextFile(directory + 'weekList.txt'); for (daWeek in listOfWeeks) { var path:String = directory + daWeek + '.json'; if (FileSystem.exists(path)) { addWeek(daWeek, path, directories[i], i, originalLength); } } for (file in FileSystem.readDirectory(directory)) { var path = haxe.io.Path.join([directory, file]); if (!FileSystem.isDirectory(path) && file.endsWith('.json')) { addWeek(file.substr(0, file.length - 5), path, directories[i], i, originalLength); } } } } #end } private static function addWeek(weekToCheck:String, path:String, directory:String, i:Int, originalLength:Int) { if (!weeksLoaded.exists(weekToCheck)) { var week:WeekFile = getWeekFile(path); if (week != null) { var weekFile:WeekData = new WeekData(week, weekToCheck); if (i >= originalLength) { #if MODS_ALLOWED weekFile.folder = directory.substring(Paths.mods().length, directory.length - 1); #end } if ((PlayState.isStoryMode && !weekFile.hideStoryMode) || (!PlayState.isStoryMode && !weekFile.hideFreeplay)) { weeksLoaded.set(weekToCheck, weekFile); weeksList.push(weekToCheck); } } } } private static function getWeekFile(path:String):WeekFile { var rawJson:String = null; #if MODS_ALLOWED if (FileSystem.exists(path)) { rawJson = File.getContent(path); } #else if (OpenFlAssets.exists(path)) { rawJson = Assets.getText(path); } #end if (rawJson != null && rawJson.length > 0) { return cast tjson.TJSON.parse(rawJson); } return null; } // FUNCTIONS YOU WILL PROBABLY NEVER NEED TO USE // To use on PlayState.hx or Highscore stuff public static function getWeekFileName():String { return weeksList[PlayState.storyWeek]; } // Used on LoadingState, nothing really too relevant public static function getCurrentWeek():WeekData { return weeksLoaded.get(weeksList[PlayState.storyWeek]); } public static function setDirectoryFromWeek(?data:WeekData = null) { Mods.currentModDirectory = ''; if (data != null && data.folder != null && data.folder.length > 0) { Mods.currentModDirectory = data.folder; } } }
0
0.900562
1
0.900562
game-dev
MEDIA
0.37115
game-dev
0.939794
1
0.939794
lzk228/space-axolotl-14
6,013
Content.Client/Damage/DamageVisualsComponent.cs
using Content.Shared.FixedPoint; namespace Content.Client.Damage; [RegisterComponent] public sealed partial class DamageVisualsComponent : Component { /// <summary> /// Damage thresholds between damage state changes. /// /// If there are any negative thresholds, or there is /// less than one threshold, the visualizer is marked /// as invalid. /// </summary> /// <remarks> /// A 'zeroth' threshold is automatically added, /// and this list is automatically sorted for /// efficiency beforehand. As such, the zeroth /// threshold is not required - and negative /// thresholds are automatically caught as /// invalid. The zeroth threshold automatically /// sets all layers to invisible, so a sprite /// isn't required for it. /// </remarks> [DataField("thresholds", required: true)] public List<FixedPoint2> Thresholds = new(); /// <summary> /// Layers to target, by layerMapKey. /// If a target layer map key is invalid /// (in essence, undefined), then the target /// layer is removed from the list for efficiency. /// /// If no layers are valid, then the visualizer /// is marked as invalid. /// /// If this is not defined, however, the visualizer /// instead adds an overlay to the sprite. /// </summary> /// <remarks> /// Layers can be disabled here by passing /// the layer's name as a key to SetData, /// and passing in a bool set to either 'false' /// to disable it, or 'true' to enable it. /// Setting the layer as disabled will make it /// completely invisible. /// </remarks> [DataField("targetLayers")] public List<Enum>? TargetLayers; /// <summary> /// The actual sprites for every damage group /// that the entity should display visually. /// /// This is keyed by a damage group identifier /// (for example, Brute), and has a value /// of a DamageVisualizerSprite (see below) /// </summary> [DataField("damageOverlayGroups")] public Dictionary<string, DamageVisualizerSprite>? DamageOverlayGroups; /// <summary> /// Sets if you want sprites to overlay the /// entity when damaged, or if you would /// rather have each target layer's state /// replaced by a different state /// within its RSI. /// /// This cannot be set to false if: /// - There are no target layers /// - There is no damage group /// </summary> [DataField("overlay")] public bool Overlay = true; /// <summary> /// A single damage group to target. /// This should only be defined if /// overlay is set to false. /// If this is defined with damageSprites, /// this will be ignored. /// </summary> /// <remarks> /// This is here because otherwise, /// you would need several permutations /// of group sprites depending on /// what kind of damage combination /// you would want, on which threshold. /// </remarks> [DataField("damageGroup")] public string? DamageGroup; /// <summary> /// Set this if you want incoming damage to be /// divided. /// </summary> /// <remarks> /// This is more useful if you have similar /// damage sprites in between entities, /// but with different damage thresholds /// and you want to avoid duplicating /// these sprites. /// </remarks> [DataField("damageDivisor")] public float Divisor = 1; /// <summary> /// Set this to track all damage, instead of specific groups. /// </summary> /// <remarks> /// This will only work if you have damageOverlay /// defined - otherwise, it will not work. /// </remarks> [DataField("trackAllDamage")] public bool TrackAllDamage; /// <summary> /// This is the overlay sprite used, if _trackAllDamage is /// enabled. Supports no complex per-group layering, /// just an actually simple damage overlay. See /// DamageVisualizerSprite for more information. /// </summary> [DataField("damageOverlay")] public DamageVisualizerSprite? DamageOverlay; public readonly List<Enum> TargetLayerMapKeys = new(); public bool Disabled = false; public bool Valid = true; public FixedPoint2 LastDamageThreshold = FixedPoint2.Zero; public readonly Dictionary<object, bool> DisabledLayers = new(); public readonly Dictionary<object, string> LayerMapKeyStates = new(); public readonly Dictionary<string, FixedPoint2> LastThresholdPerGroup = new(); public string TopMostLayerKey = default!; } // deals with the edge case of human damage visuals not // being in color without making a Dict<Dict<Dict<Dict<Dict<Dict... [DataDefinition] public sealed partial class DamageVisualizerSprite { /// <summary> /// The RSI path for the damage visualizer /// group overlay. /// </summary> /// <remarks> /// States in here will require one of four /// forms: /// /// If tracking damage groups: /// - {base_state}_{group}_{threshold} if targeting /// a static layer on a sprite (either as an /// overlay or as a state change) /// - DamageOverlay_{group}_{threshold} if not /// targeting a layer on a sprite. /// /// If not tracking damage groups: /// - {base_state}_{threshold} if it is targeting /// a layer /// - DamageOverlay_{threshold} if not targeting /// a layer. /// </remarks> [DataField("sprite", required: true)] public string Sprite = default!; /// <summary> /// The color of this sprite overlay. /// Supports only hexadecimal format. /// </summary> [DataField("color")] public string? Color; }
0
0.825596
1
0.825596
game-dev
MEDIA
0.841321
game-dev
0.777228
1
0.777228