Here are the examples of the csharp api System.Collections.Generic.List.Add(ushort) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
287 Examples
19
Source : Formatter.Array1.List.cs
with MIT License
from 1996v
with MIT License
from 1996v
public List<UInt16> Deserialize(ref BssomReader reader, ref BssomDeserializeContext context)
{
if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.UInt16Code))
{
return default;
}
context.Option.Security.DepthStep(ref context);
reader.SkipVariableNumber();
int len = reader.ReadVariableNumber();
List<ushort> val = new List<UInt16>(len);
for (int i = 0; i < len; i++)
{
val.Add(reader.ReadUInt16WithOutTypeHead());
}
context.Depth--;
return val;
}
19
Source : Server.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
private void Update()
{
// Network Tick.
lock (instantiateJobs)
{
for (int i = 0; i < instantiateJobs.Count; i++)
{
(User user, ushort id) = instantiateJobs[i];
var obj = Instantiate(playerPrefab, Vector3.zero, Quaternion.idenreplacedy);
var tmpPlayer = obj.GetComponent<Player>();
tmpPlayer.SetPlayerID(id);
user.player = tmpPlayer;
// Attach the Lag compensation module to the new instantiated player.
obj.AddComponent<LagCompensationModule>().Init(user.player);
}
instantiateJobs.Clear();
}
lock (disconnectedClients)
{
foreach (var clientSock in clients.Keys)
{
if (clients[clientSock].player.playerContainer == null)
{
OnUserDisconnect(clientSock);
}
}
foreach (var disconnectedSock in disconnectedClients)
{
var playerId = clients[disconnectedSock].player.playerId;
if (clients[disconnectedSock].player.playerContainer != null)
{
GameObject.Destroy(clients[disconnectedSock].player.playerContainer);
}
lock (clients)
{
clients.Remove(disconnectedSock);
}
lock (playerIdList)
{
playerIdList.Add(playerId);
// return the id number to the id pool for new players to join in.
Console.WriteLine("Client Disconnected, Returned Player ID: " + playerId);
Console.WriteLine("Player Count: " + (MaximumPlayers - playerIdList.Count) + " / " + MaximumPlayers);
}
}
disconnectedClients.Clear();
}
// Every tick we call update function which will process all the user commands and apply them to the physics world.
serverLoop.Update(clients.Values.Select(x => x.player).ToList());
WorldState snapshot = serverLoop.GetSnapshot();
lock (OutputsOG)
{
for (int i = OutputsOG.Count - 1; i >= 0; i--)
{
var sock = OutputsOG[i];
try
{
SendSnapshot(sock, snapshot);
}
catch
{
OnUserDisconnect(sock);
}
}
}
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void CreateIndex(IEnumerable<KeyValuePair<Guid, Example>> examples)
{
var ex = examples.ToList();
foreach (var example in ex)
{
string lines = GetTextFromExample(example.Value);
var terms = GetTerms(lines);
// Memory optimisation. Store term indices as ushort (16bit)
if (terms.Count > ushort.MaxValue)
throw new InvalidOperationException("Too many terms in this example: " + example.Value.replacedle);
var termDictExample = new Dictionary<string, List<ushort>>();
for (ushort i = 0; i < terms.Count; i++)
{
var term = terms[i];
if (termDictExample.ContainsKey(term))
{
termDictExample[term].Add(i);
}
else
{
termDictExample[term] = new List<ushort> { i };
}
}
var norm = Math.Sqrt(termDictExample.Sum(termDict => Sqr(termDict.Value.Count)));
foreach (var termDict in termDictExample)
{
var term = termDict.Key;
termDict.Value.TrimExcess();
if (_invertedIndex.ContainsKey(term))
{
var ti = new TermInfo(example.Key, termDict.Value.ToArray(), (float) (termDict.Value.Count / norm));
_invertedIndex[term].TermInfos.Add(ti);
}
else
{
_invertedIndex[term] = new Posting(new List<TermInfo>
{
new TermInfo(example.Key, termDict.Value.ToArray(), (float) (termDict.Value.Count/norm))
});
}
_invertedIndex[term].InvertedDoreplacedentFrequency += 1;
}
}
_invertedIndex.ForEachDo(
x => x.Value.InvertedDoreplacedentFrequency = Math.Log(ex.Count/x.Value.InvertedDoreplacedentFrequency));
}
19
Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void CreateIndexForCode(IEnumerable<KeyValuePair<Guid, Example>> examples)
{
var ex = examples.ToList();
foreach (var example in ex)
{
var tokenizer = new NGramTokenizer();
string lines = GetSourceCodeFromExample(example.Value);
var terms = lines.ToLower().Split(' ').Where(x => x != "")
.Select(tokenizer.Tokenize)
.SelectMany(strings => strings.SelectMany(inner => inner))
.Select(sb => sb.ToString())
.Where(s => !string.IsNullOrEmpty(s) && s.Length > 1)
.ToList();
// Memory optimisation. Store term indices as ushort (16bit)
if (terms.Count > ushort.MaxValue)
throw new InvalidOperationException("Too many code terms for example: " + example.Value.replacedle);
var termDictExample = new Dictionary<string, List<ushort>>();
for (ushort i = 0; i < terms.Count; i++)
{
var term = terms[i];
if (termDictExample.ContainsKey(term))
{
termDictExample[term].Add(i);
}
else
{
termDictExample[term] = new List<ushort> { i };
}
}
var norm = Math.Sqrt(termDictExample.Sum(termDict => Sqr(termDict.Value.Count)));
foreach (var termDict in termDictExample)
{
var term = termDict.Key;
var list = termDict.Value;
if (_codeInvertedIndex.ContainsKey(term))
{
var ti = new TermInfo(example.Key, termDict.Value.ToArray(), (float) (termDict.Value.Count / norm));
_codeInvertedIndex[term].TermInfos.Add(ti);
}
else
{
var ti = new TermInfo(example.Key, termDict.Value.ToArray(), (float)(termDict.Value.Count / norm));
_codeInvertedIndex[term] = new Posting(new List<TermInfo>
{
ti,
});
}
_codeInvertedIndex[term].InvertedDoreplacedentFrequency += 1;
}
}
_codeInvertedIndex.ForEachDo(x =>
{
x.Value.InvertedDoreplacedentFrequency = Math.Log(ex.Count/x.Value.InvertedDoreplacedentFrequency);
// Collapse memory of List<TermInfo>
x.Value.TermInfos = x.Value.TermInfos.ToList();
});
}
19
Source : BSPNode.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public virtual void Unpack(BinaryReader reader, BSPType treeType)
{
Type = Encoding.ASCII.GetString(reader.ReadBytes(4)).Reverse();
switch (Type)
{
// These types will unpack the data completely, in their own clreplacedes
case "PORT":
case "LEAF":
throw new Exception();
}
SplittingPlane = new Plane();
SplittingPlane.Unpack(reader);
switch (Type)
{
case "BPnn":
case "BPIn":
PosNode = BSPNode.ReadNode(reader, treeType);
break;
case "BpIN":
case "BpnN":
NegNode = BSPNode.ReadNode(reader, treeType);
break;
case "BPIN":
case "BPnN":
PosNode = BSPNode.ReadNode(reader, treeType);
NegNode = BSPNode.ReadNode(reader, treeType);
break;
}
if (treeType == BSPType.Cell)
return;
Sphere = new Sphere();
Sphere.Unpack(reader);
if (treeType == BSPType.Physics)
return;
InPolys = new List<ushort>();
uint numPolys = reader.ReadUInt32();
for (uint i = 0; i < numPolys; i++)
InPolys.Add(reader.ReadUInt16());
}
19
Source : CBldPortal.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void Unpack(BinaryReader reader)
{
Flags = (PortalFlags)reader.ReadUInt16();
OtherCellId = reader.ReadUInt16();
OtherPortalId = reader.ReadUInt16();
ushort num_stabs = reader.ReadUInt16();
for (var i = 0; i < num_stabs; i++)
StabList.Add(reader.ReadUInt16());
reader.AlignBoundary();
}
19
Source : CellStruct.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void Unpack(BinaryReader reader)
{
var numPolygons = reader.ReadUInt32();
var numPhysicsPolygons = reader.ReadUInt32();
var numPortals = reader.ReadUInt32();
VertexArray.Unpack(reader);
Polygons.Unpack(reader, numPolygons);
for (uint i = 0; i < numPortals; i++)
Portals.Add(reader.ReadUInt16());
reader.AlignBoundary();
CellBSP.Unpack(reader, BSPType.Cell);
PhysicsPolygons.Unpack(reader, numPhysicsPolygons);
PhysicsBSP.Unpack(reader, BSPType.Physics);
uint hasDrawingBSP = reader.ReadUInt32();
if (hasDrawingBSP != 0)
{
DrawingBSP = new BSPTree();
DrawingBSP.Unpack(reader, BSPType.Drawing);
}
reader.AlignBoundary();
}
19
Source : CellLandblock.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override void Unpack(BinaryReader reader)
{
Id = reader.ReadUInt32();
uint hasObjects = reader.ReadUInt32();
if (hasObjects == 1)
HasObjects = true;
// Read in the terrain. 9x9 so 81 records.
for (int i = 0; i < 81; i++)
{
var terrain = reader.ReadUInt16();
Terrain.Add(terrain);
}
// Read in the height. 9x9 so 81 records
for (int i = 0; i < 81; i++)
{
var height = reader.ReadByte();
Height.Add(height);
}
reader.AlignBoundary();
}
19
Source : EnvCell.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public override void Unpack(BinaryReader reader)
{
Id = reader.ReadUInt32();
Flags = (EnvCellFlags)reader.ReadUInt32();
reader.BaseStream.Position += 4; // Skip ahead 4 bytes, because this is the CellId. Again. Twice.
byte numSurfaces = reader.ReadByte();
byte numPortals = reader.ReadByte(); // Note that "portal" in this context does not refer to the swirly pink/purple thing, its basically connecting cells
ushort numStabs = reader.ReadUInt16(); // I believe this is what cells can be seen from this one. So the engine knows what else it needs to load/draw.
// Read what surfaces are used in this cell
for (uint i = 0; i < numSurfaces; i++)
Surfaces.Add(0x08000000u | reader.ReadUInt16()); // these are stored in the dat as short values, so we'll make them a full dword
EnvironmentId = (0x0D000000u | reader.ReadUInt16());
CellStructure = reader.ReadUInt16();
Position.Unpack(reader);
CellPortals.Unpack(reader, numPortals);
for (uint i = 0; i < numStabs; i++)
VisibleCells.Add(reader.ReadUInt16());
if ((Flags & EnvCellFlags.HreplacedtaticObjs) != 0)
StaticObjects.Unpack(reader);
if ((Flags & EnvCellFlags.HasRestrictionObj) != 0)
RestrictionObj = reader.ReadUInt32();
}
19
Source : BldPortal.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void add_to_stablist(ref List<ushort> stabList, ref uint maxSize, ref uint stabNum)
{
// is maxSize needed with list?
for (var i = 0; i < StabList.Count; i++)
{
var j = (int)stabNum;
while (j > 0)
{
if (StabList[i] == stabList[j - 1])
break;
j--;
}
if (j > 0)
{
if (stabNum >= maxSize)
{
var old = stabList;
stabList = new List<ushort>();
maxSize += 10;
foreach (var stab in StabList)
stabList.Add(stab);
}
stabList.Add(StabList[i]);
stabNum++;
}
}
}
19
Source : Polygon.cs
with GNU General Public License v3.0
from ACEmulator
with GNU General Public License v3.0
from ACEmulator
public void BuildIndices()
{
Indices = new List<ushort>();
ushort firstIdx = 0;
ushort lastIdx = 0;
for (var i = 0; i < _polygon.VertexIds.Count; i++)
{
var vertID = _polygon.VertexIds[i];
ushort uvIdx = 0;
if (_polygon.PosUVIndices != null && i < _polygon.PosUVIndices.Count)
{
uvIdx = _polygon.PosUVIndices[i];
}
var key = new Tuple<ushort, ushort>((ushort)vertID, uvIdx);
if (!UVLookup.TryGetValue(key, out var idx))
{
Console.WriteLine($"Couldn't find UV for {GfxObj._gfxObj.Id:X8} key {key}");
continue;
}
if (i == 0)
firstIdx = idx;
if (i > 2)
{
// make triangle fan
Indices.Add(firstIdx);
Indices.Add(lastIdx);
}
lastIdx = idx;
Indices.Add(idx);
}
//Console.WriteLine($"Poly verts: {_polygon.VertexIds.Count} ({IndexArray.Count})");
}
19
Source : WksRecord.cs
with Apache License 2.0
from alexreinert
with Apache License 2.0
from alexreinert
internal override void ParseRecordData(byte[] resultData, int currentPosition, int length)
{
int endPosition = currentPosition + length;
Address = new IPAddress(DnsMessageBase.ParseByteData(resultData, ref currentPosition, 4));
Protocol = (ProtocolType) resultData[currentPosition++];
Ports = new List<ushort>();
int octetNumber = 0;
while (currentPosition < endPosition)
{
byte octet = resultData[currentPosition++];
for (int bit = 0; bit < 8; bit++)
{
if ((octet & (1 << Math.Abs(bit - 7))) != 0)
{
Ports.Add((ushort) (octetNumber * 8 + bit));
}
}
octetNumber++;
}
}
19
Source : ModbusDevice.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void SetCoil(ushort address, bool value)
{
using (coilsLock.GetWriteLock())
{
if (value && !coils.Contains(address))
{
coils.Add(address);
}
if (!value && coils.Contains(address))
{
coils.Remove(address);
}
}
}
19
Source : ModbusDevice.cs
with MIT License
from AndreasAmMueller
with MIT License
from AndreasAmMueller
public void SetInput(ushort address, bool value)
{
using (discreteInputsLock.GetWriteLock())
{
if (value && !discreteInputs.Contains(address))
{
discreteInputs.Add(address);
}
if (!value && discreteInputs.Contains(address))
{
discreteInputs.Remove(address);
}
}
}
19
Source : UniGifDecoder.cs
with MIT License
from andrew-raphael-lukasik
with MIT License
from andrew-raphael-lukasik
static async Task<GifTexture[]> DecodeTexturesAsync
(
GifData gifData ,
FilterMode filterMode ,
TextureWrapMode wrapMode
)
{
if( gifData.m_imageBlockList==null || gifData.m_imageBlockList.Count<1 )
{
await Task.Delay( 1 );//yield break;
}
List<GifTexture> gifTexList = new List<GifTexture>( gifData.m_imageBlockList.Count );
List<ushort> disposalMethodList = new List<ushort>( gifData.m_imageBlockList.Count );
int imgIndex = 0;
for( int i = 0 ; i<gifData.m_imageBlockList.Count ; i++ )
{
byte[] decodedData = GetDecodedData( gifData.m_imageBlockList[i] );
GraphicControlExtension? graphicCtrlEx = GetGraphicCtrlExt( gifData , imgIndex );
int transparentIndex = GetTransparentIndex( graphicCtrlEx );
disposalMethodList.Add( GetDisposalMethod( graphicCtrlEx ) );
Color32 bgColor;
List<byte[]> colorTable = GetColorTableAndSetBgColor( gifData , gifData.m_imageBlockList[i] , transparentIndex , out bgColor );
await Task.Delay( 1 );//yield return 0;
bool filledTexture;
Texture2D tex = CreateTexture2D( gifData , gifTexList , imgIndex , disposalMethodList , bgColor , filterMode , wrapMode , out filledTexture );
await Task.Delay( 1 );//yield return 0;
// Set pixel data
int dataIndex = 0;
// Reverse set pixels. because GIF data starts from the top left.
for( int y = tex.height - 1 ; y>=0 ; y-- )
{
SetTexturePixelRow( tex , y , gifData.m_imageBlockList[i] , decodedData , ref dataIndex , colorTable , bgColor , transparentIndex , filledTexture );
}
tex.Apply();
await Task.Delay( 1 );//yield return 0;
float delaySec = GetDelaySec( graphicCtrlEx );
// Add to GIF texture list
gifTexList.Add( new GifTexture( tex , delaySec ) );
imgIndex++;
}
return gifTexList.ToArray();
}
19
Source : UniGifDecoder.cs
with MIT License
from andrew-raphael-lukasik
with MIT License
from andrew-raphael-lukasik
static async Task<Texture2D> DecodeTextureAsync
(
GifData gifData ,
FilterMode filterMode ,
TextureWrapMode wrapMode
)
{
if( gifData.m_imageBlockList==null || gifData.m_imageBlockList.Count<1 )
{
await Task.Delay( 1 );
}
List<ushort> disposalMethodList = new List<ushort>( gifData.m_imageBlockList.Count );
int imgIndex = 0;
int i = 0;
byte[] decodedData = GetDecodedData( gifData.m_imageBlockList[i] );
GraphicControlExtension? graphicCtrlEx = GetGraphicCtrlExt( gifData , imgIndex );
int transparentIndex = GetTransparentIndex( graphicCtrlEx );
disposalMethodList.Add( GetDisposalMethod( graphicCtrlEx ) );
Color32 bgColor;
List<byte[]> colorTable = GetColorTableAndSetBgColor( gifData , gifData.m_imageBlockList[i] , transparentIndex , out bgColor );
await Task.Delay( 1 );
bool filledTexture;
Texture2D texture = CreateTexture2D( gifData , imgIndex , disposalMethodList , bgColor , filterMode , wrapMode , out filledTexture );
await Task.Delay( 1 );
// Set pixel data
int dataIndex = 0;
// Reverse set pixels. because GIF data starts from the top left.
for( int y = texture.height - 1 ; y>=0 ; y-- )
{
SetTexturePixelRow( texture , y , gifData.m_imageBlockList[i] , decodedData , ref dataIndex , colorTable , bgColor , transparentIndex , filledTexture );
}
texture.Apply();
await Task.Delay( 1 );
float delaySec = GetDelaySec( graphicCtrlEx );
imgIndex++;
return texture;
}
19
Source : ItemExtensions.cs
with GNU General Public License v3.0
from berichan
with GNU General Public License v3.0
from berichan
private static void checkInternalList()
{
if (itemsInternal == null)
{
itemsInternal = new List<ushort>();
string[] hexes = ResourceLoader.GetInternalHexes().text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string h in hexes)
itemsInternal.Add(ushort.Parse(h, System.Globalization.NumberStyles.HexNumber));
}
}
19
Source : Utils.cs
with MIT License
from bradhannah
with MIT License
from bradhannah
public static List<ushort> CreateOffsetList(byte[] byteArray, int offset, int length)
{
List<ushort> offsetArray = new List<ushort>();
// double TOTAL_LOOKS because we are using 16 bit integers, using two bytes at a time
for (int i = 0; i < length; i += 2)
{
offsetArray.Add((ushort)(byteArray[i] | (byteArray[i + 1] << 8)));
}
return offsetArray;
}
19
Source : FixedMemoryBlock.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public List<ushort> ReadUShorts(long offset, int count)
{
List<ushort> re = new List<ushort>(count);
for (int i = 0; i < count; i++)
{
re.Add(ReadUShort((int)offset + 2 * i));
}
return re;
}
19
Source : HisDataBuffer.cs
with Apache License 2.0
from cdy816
with Apache License 2.0
from cdy816
public List<ushort> ReadUShorts(long offset, int count)
{
List<ushort> re = new List<ushort>(count);
for (int i = 0; i < count; i++)
{
re.Add(ReadUShort(offset + 2 * i));
}
return re;
}
19
Source : SctpErrorChunk.cs
with MIT License
from chatop2020
with MIT License
from chatop2020
public static SctpErrorChunk ParseChunk(byte[] buffer, int posn, bool isAbort)
{
var errorChunk = (isAbort) ? new SctpAbortChunk(false) : new SctpErrorChunk();
ushort chunkLen = errorChunk.ParseFirstWord(buffer, posn);
int paramPosn = posn + SCTP_CHUNK_HEADER_LENGTH;
int paramsBufferLength = chunkLen - SCTP_CHUNK_HEADER_LENGTH;
if (paramPosn < paramsBufferLength)
{
bool stopProcessing = false;
foreach (var varParam in GetParameters(buffer, paramPosn, paramsBufferLength))
{
switch (varParam.ParameterType)
{
case (ushort)SctpErrorCauseCode.InvalidStreamIdentifier:
ushort streamID = (ushort)((varParam.ParameterValue != null) ?
NetConvert.ParseUInt16(varParam.ParameterValue, 0) : 0);
var invalidStreamID = new SctpErrorInvalidStreamIdentifier { StreamID = streamID };
errorChunk.AddErrorCause(invalidStreamID);
break;
case (ushort)SctpErrorCauseCode.MissingMandatoryParameter:
List<ushort> missingIDs = new List<ushort>();
if (varParam.ParameterValue != null)
{
for (int i = 0; i < varParam.ParameterValue.Length; i += 2)
{
missingIDs.Add(NetConvert.ParseUInt16(varParam.ParameterValue, i));
}
}
var missingMandatory = new SctpErrorMissingMandatoryParameter { MissingParameters = missingIDs };
errorChunk.AddErrorCause(missingMandatory);
break;
case (ushort)SctpErrorCauseCode.StaleCookieError:
uint staleness = (uint)((varParam.ParameterValue != null) ?
NetConvert.ParseUInt32(varParam.ParameterValue, 0) : 0);
var staleCookie = new SctpErrorStaleCookieError { MeasureOfStaleness = staleness };
errorChunk.AddErrorCause(staleCookie);
break;
case (ushort)SctpErrorCauseCode.OutOfResource:
errorChunk.AddErrorCause(new SctpCauseOnlyError(SctpErrorCauseCode.OutOfResource));
break;
case (ushort)SctpErrorCauseCode.UnresolvableAddress:
var unresolvable = new SctpErrorUnresolvableAddress { UnresolvableAddress = varParam.ParameterValue };
errorChunk.AddErrorCause(unresolvable);
break;
case (ushort)SctpErrorCauseCode.UnrecognizedChunkType:
var unrecognised = new SctpErrorUnrecognizedChunkType { UnrecognizedChunk = varParam.ParameterValue };
errorChunk.AddErrorCause(unrecognised);
break;
case (ushort)SctpErrorCauseCode.InvalidMandatoryParameter:
errorChunk.AddErrorCause(new SctpCauseOnlyError(SctpErrorCauseCode.InvalidMandatoryParameter));
break;
case (ushort)SctpErrorCauseCode.UnrecognizedParameters:
var unrecognisedParams = new SctpErrorUnrecognizedParameters { UnrecognizedParameters = varParam.ParameterValue };
errorChunk.AddErrorCause(unrecognisedParams);
break;
case (ushort)SctpErrorCauseCode.NoUserData:
uint tsn = (uint)((varParam.ParameterValue != null) ?
NetConvert.ParseUInt32(varParam.ParameterValue, 0) : 0);
var noData = new SctpErrorNoUserData { TSN = tsn };
errorChunk.AddErrorCause(noData);
break;
case (ushort)SctpErrorCauseCode.CookieReceivedWhileShuttingDown:
errorChunk.AddErrorCause(new SctpCauseOnlyError(SctpErrorCauseCode.CookieReceivedWhileShuttingDown));
break;
case (ushort)SctpErrorCauseCode.RestartreplacedociationWithNewAddress:
var restartAddress = new SctpErrorRestartreplacedociationWithNewAddress
{ NewAddressTLVs = varParam.ParameterValue };
errorChunk.AddErrorCause(restartAddress);
break;
case (ushort)SctpErrorCauseCode.UserInitiatedAbort:
string reason = (varParam.ParameterValue != null) ?
Encoding.UTF8.GetString(varParam.ParameterValue) : null;
var userAbort = new SctpErrorUserInitiatedAbort { AbortReason = reason };
errorChunk.AddErrorCause(userAbort);
break;
case (ushort)SctpErrorCauseCode.ProtocolViolation:
string info = (varParam.ParameterValue != null) ?
Encoding.UTF8.GetString(varParam.ParameterValue) : null;
var protocolViolation = new SctpErrorProtocolViolation { AdditionalInformation = info };
errorChunk.AddErrorCause(protocolViolation);
break;
default:
// Parameter was not recognised.
errorChunk.GotUnrecognisedParameter(varParam);
break;
}
if (stopProcessing)
{
logger.LogWarning($"SCTP unrecognised parameter {varParam.ParameterType} for chunk type {SctpChunkType.ERROR} "
+ "indicated no further chunks should be processed.");
break;
}
}
}
return errorChunk;
}
19
Source : UniGifDecoder.cs
with MIT License
from chiepomme
with MIT License
from chiepomme
private static IEnumerator DecodeTextureCoroutine(GifData gifData, Action<List<GifTexture>> callback, FilterMode filterMode, TextureWrapMode wrapMode)
{
if (gifData.m_imageBlockList == null || gifData.m_imageBlockList.Count < 1)
{
yield break;
}
List<GifTexture> gifTexList = new List<GifTexture>(gifData.m_imageBlockList.Count);
List<ushort> disposalMethodList = new List<ushort>(gifData.m_imageBlockList.Count);
int imgIndex = 0;
for (int i = 0; i < gifData.m_imageBlockList.Count; i++)
{
byte[] decodedData = GetDecodedData(gifData.m_imageBlockList[i]);
GraphicControlExtension? graphicCtrlEx = GetGraphicCtrlExt(gifData, imgIndex);
int transparentIndex = GetTransparentIndex(graphicCtrlEx);
disposalMethodList.Add(GetDisposalMethod(graphicCtrlEx));
Color32 bgColor;
List<byte[]> colorTable = GetColorTableAndSetBgColor(gifData, gifData.m_imageBlockList[i], transparentIndex, out bgColor);
yield return 0;
bool filledTexture;
Texture2D tex = CreateTexture2D(gifData, gifTexList, imgIndex, disposalMethodList, bgColor, filterMode, wrapMode, out filledTexture);
yield return 0;
// Set pixel data
int dataIndex = 0;
// Reverse set pixels. because GIF data starts from the top left.
for (int y = tex.height - 1; y >= 0; y--)
{
SetTexturePixelRow(tex, y, gifData.m_imageBlockList[i], decodedData, ref dataIndex, colorTable, bgColor, transparentIndex, filledTexture);
}
tex.Apply();
yield return 0;
float delaySec = GetDelaySec(graphicCtrlEx);
// Add to GIF texture list
gifTexList.Add(new GifTexture(tex, delaySec));
imgIndex++;
}
if (callback != null)
{
callback(gifTexList);
}
yield break;
}
19
Source : AutoTimedTrafficLights.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
private static List<ushort> OneWayRoads(ushort nodeId, out int count) {
List<ushort> segList2 = new List<ushort>();
ref NetNode node = ref Singleton<NetManager>.instance.m_nodes.m_buffer[nodeId];
for (int i = 0; i < 8; ++i) {
var segId = node.GetSegment(i);
if (segMan.CalculateIsOneWay(segId)) {
segList2.Add(segId);
}
}
count = segList2.Count;
return segList2;
}
19
Source : PriorityRoad.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
public static IRecordable FixRoad(ushort initialSegmentId) {
// Create segment list such that the first and last segments are at path end.
List<ushort> segmentList = new List<ushort>(40);
SegmentTraverser.Traverse(
initialSegmentId,
TraverseDirection.AnyDirection,
TraverseSide.Straight,
SegmentStopCriterion.None,
data => {
if (data.ViaInitialStartNode)
segmentList.Add(data.CurSeg.segmentId);
else
segmentList.Insert(0, data.CurSeg.segmentId);
return true;
});
return FixRoad(segmentList);
}
19
Source : PriorityRoad.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
internal static List<ushort> GetNodeSegments(ushort nodeId) {
List<ushort> segmentList = new List<ushort>();
for (int i = 0; i < 8; ++i) {
ushort segId = nodeId.ToNode().GetSegment(i);
if (segId != 0) {
segmentList.Add(segId);
}
}
return segmentList;
}
19
Source : PriorityRoad.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
public static void FixHighPriorityJunction(ushort nodeId, List<ushort> segmentList) {
if (nodeId == 0) {
return;
}
List<ushort> nodeSegments = new List<ushort>();
for (int i = 0; i < 8; ++i) {
ushort segId = nodeId.ToNode().GetSegment(i);
if (segId != 0) {
bool main = segmentList.Contains(segId);
if (main) {
nodeSegments.Insert(0, segId);
} else {
nodeSegments.Add(segId);
}
}
}
if (nodeSegments.Count < 3) {
Log._Debug("FixJunction: This is not a junction. nodeID=" + nodeId);
return;
}
FixHighPriorityJunctionHelper(nodeId, nodeSegments);
}
19
Source : RoundaboutMassEdit.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
private bool TraverseAroundRecursive(ushort segmentId) {
if (segmentList_.Count > 20) {
return false; // too long. prune
}
segmentList_.Add(segmentId);
var segments = GetSortedSegments(segmentId);
foreach (var nextSegmentId in segments) {
bool isRoundabout;
if (nextSegmentId == segmentList_[0]) {
isRoundabout = true;
} else if (Contains(nextSegmentId)) {
isRoundabout = false; // try another segment.
} else {
isRoundabout = TraverseAroundRecursive(nextSegmentId);
}
if (isRoundabout) {
return true;
} //end if
}// end foreach
segmentList_.Remove(segmentId);
return false;
}
19
Source : GetNodeSegmentIdsEnumerableTests.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
[TestMethod]
public void Foreach_InitialSegmentId1_Clockwise() {
var testSegments = new NetSegment[] {
default,
new NetSegment() {
m_startNode = 1,
m_endNode = 1,
m_startLeftSegment = 2,
m_startRightSegment = 4,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 2,
m_startLeftSegment = 3,
m_startRightSegment = 1,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 3,
m_startLeftSegment = 4,
m_startRightSegment = 2,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 4,
m_startLeftSegment = 1,
m_startRightSegment = 3,
},
};
var expected = new List<ushort> { 1, 2, 3, 4 };
var actual = new List<ushort>();
foreach (var item in new GetNodeSegmentIdsEnumerable(1, 1, ClockDirection.Clockwise, testSegments)) {
actual.Add(item);
}
Collectionreplacedert.AreEqual(expected, actual);
}
19
Source : GetNodeSegmentIdsEnumerableTests.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
[TestMethod]
public void Foreach_StartAt1_Clockwise_TwoTimes() {
var testSegments = new NetSegment[] {
default,
new NetSegment() {
m_startNode = 1,
m_endNode = 1,
m_startLeftSegment = 2,
m_startRightSegment = 4,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 2,
m_startLeftSegment = 3,
m_startRightSegment = 1,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 3,
m_startLeftSegment = 4,
m_startRightSegment = 2,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 4,
m_startLeftSegment = 1,
m_startRightSegment = 3,
},
};
var expected = new List<ushort> { 1, 2, 3, 4 };
var actual1 = new List<ushort>();
var actual2 = new List<ushort>();
foreach (var item in new GetNodeSegmentIdsEnumerable(1, 1, ClockDirection.Clockwise, testSegments)) {
actual1.Add(item);
}
foreach (var item in new GetNodeSegmentIdsEnumerable(1, 1, ClockDirection.Clockwise, testSegments)) {
actual2.Add(item);
}
Collectionreplacedert.AreEqual(expected, actual1);
Collectionreplacedert.AreEqual(expected, actual2);
}
19
Source : GetNodeSegmentIdsEnumerableTests.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
[TestMethod]
public void Foreach_ViaInterface_InitialSegmentId1_Clockwise() {
var testSegments = new NetSegment[] {
default,
new NetSegment() {
m_startNode = 1,
m_endNode = 1,
m_startLeftSegment = 2,
m_startRightSegment = 4,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 2,
m_startLeftSegment = 3,
m_startRightSegment = 1,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 3,
m_startLeftSegment = 4,
m_startRightSegment = 2,
},
new NetSegment() {
m_startNode = 1,
m_endNode = 4,
m_startLeftSegment = 1,
m_startRightSegment = 3,
},
};
var expected = new List<ushort> { 1, 2, 3, 4 };
var actual = new List<ushort>();
IEnumerable<ushort> nodeSegmentIds = new GetNodeSegmentIdsEnumerable(1, 1, ClockDirection.Clockwise, testSegments);
foreach (var item in nodeSegmentIds) {
actual.Add(item);
}
Collectionreplacedert.AreEqual(expected, actual);
}
19
Source : ArrayHandler.cs
with MIT License
from CitiesSkylinesMultiplayer
with MIT License
from CitiesSkylinesMultiplayer
public static void Postfix(ref ushort item)
{
if (_collecting)
{
_array16Collected.Add(item);
}
}
19
Source : AutoTimedTrafficLights.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
private static List<ushort> ArrangedSegments(ushort nodeId) {
ClockDirection clockDirection = Shortcuts.LHT
? ClockDirection.CounterClockwise
: ClockDirection.Clockwise;
List<ushort> segList = new List<ushort>();
foreach (var segmentId in netService.GetNodeSegmentIds(nodeId, clockDirection)) {
if (CountOutgoingLanes(segmentId, nodeId) > 0) {
segList.Add(segmentId);
}
}
return segList;
}
19
Source : TrafficLightSimulationManager.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
public bool LoadData(List<Configuration.TimedTrafficLights> data) {
bool success = true;
Log.Info($"Loading {data.Count} timed traffic lights (new method)");
var nodesWithSimulation = new HashSet<ushort>();
foreach (Configuration.TimedTrafficLights cnfTimedLights in data) {
nodesWithSimulation.Add(cnfTimedLights.nodeId);
}
var masterNodeIdBySlaveNodeId = new Dictionary<ushort, ushort>();
var nodeGroupByMasterNodeId = new Dictionary<ushort, List<ushort>>();
foreach (Configuration.TimedTrafficLights cnfTimedLights in data) {
try {
// TODO most of this should not be necessary at all if the clreplacedes around TimedTrafficLights clreplaced were properly designed
// enforce uniqueness of node ids
List<ushort> currentNodeGroup = cnfTimedLights.nodeGroup.Distinct().ToList();
if (!currentNodeGroup.Contains(cnfTimedLights.nodeId)) {
currentNodeGroup.Add(cnfTimedLights.nodeId);
}
// remove any nodes that are not configured to have a simulation
currentNodeGroup = new List<ushort>(
currentNodeGroup.Intersect(nodesWithSimulation));
// remove invalid nodes from the group; find if any of the nodes in the group is already a master node
ushort masterNodeId = 0;
int foundMasterNodes = 0;
for (int i = 0; i < currentNodeGroup.Count;) {
ushort nodeId = currentNodeGroup[i];
if (!ExtNodeManager.Instance.IsValid(currentNodeGroup[i])) {
currentNodeGroup.RemoveAt(i);
continue;
}
if (nodeGroupByMasterNodeId.ContainsKey(nodeId)) {
// this is a known master node
if (foundMasterNodes > 0) {
// we already found another master node. ignore this node.
currentNodeGroup.RemoveAt(i);
continue;
}
// we found the first master node
masterNodeId = nodeId;
++foundMasterNodes;
}
++i;
}
if (masterNodeId == 0) {
// no master node defined yet, set the first node as a master node
masterNodeId = currentNodeGroup[0];
}
// ensure the master node is the first node in the list (TimedTrafficLights
// depends on this at the moment...)
currentNodeGroup.Remove(masterNodeId);
currentNodeGroup.Insert(0, masterNodeId);
// update the saved node group and master-slave info
nodeGroupByMasterNodeId[masterNodeId] = currentNodeGroup;
foreach (ushort nodeId in currentNodeGroup) {
masterNodeIdBySlaveNodeId[nodeId] = masterNodeId;
}
} catch (Exception e) {
Log.WarningFormat(
"Error building timed traffic light group for TimedNode {0} (NodeGroup: {1}): {2}",
cnfTimedLights.nodeId,
string.Join(", ", cnfTimedLights.nodeGroup.Select(x => x.ToString()).ToArray()),
e);
success = false;
}
}
foreach (Configuration.TimedTrafficLights cnfTimedLights in data) {
try {
if (!masterNodeIdBySlaveNodeId.ContainsKey(cnfTimedLights.nodeId)) {
continue;
}
ushort masterNodeId = masterNodeIdBySlaveNodeId[cnfTimedLights.nodeId];
List<ushort> nodeGroup = nodeGroupByMasterNodeId[masterNodeId];
#if DEBUGLOAD
Log._Debug($"Adding timed light at node {cnfTimedLights.nodeId}. NodeGroup: "+
$"{string.Join(", ", nodeGroup.Select(x => x.ToString()).ToArray())}");
#endif
SetUpTimedTrafficLight(cnfTimedLights.nodeId, nodeGroup);
int j = 0;
foreach (Configuration.TimedTrafficLightsStep cnfTimedStep in cnfTimedLights.timedSteps) {
#if DEBUGLOAD
Log._Debug($"Loading timed step {j} at node {cnfTimedLights.nodeId}");
#endif
ITimedTrafficLightsStep step =
TrafficLightSimulations[cnfTimedLights.nodeId].timedLight.AddStep(
cnfTimedStep.minTime,
cnfTimedStep.maxTime,
(StepChangeMetric)cnfTimedStep.changeMetric,
cnfTimedStep.waitFlowBalance);
foreach (KeyValuePair<ushort, Configuration.CustomSegmentLights> e in
cnfTimedStep.segmentLights)
{
if (!ExtSegmentManager.Instance.IsSegmentValid(e.Key)) {
continue;
}
e.Value.nodeId = cnfTimedLights.nodeId;
#if DEBUGLOAD
Log._Debug($"Loading timed step {j}, segment {e.Key} at node {cnfTimedLights.nodeId}");
#endif
ICustomSegmentLights lights = null;
if (!step.CustomSegmentLights.TryGetValue(e.Key, out lights)) {
#if DEBUGLOAD
Log._Debug($"No segment lights found at timed step {j} for segment "+
$"{e.Key}, node {cnfTimedLights.nodeId}");
#endif
continue;
}
Configuration.CustomSegmentLights cnfLights = e.Value;
#if DEBUGLOAD
Log._Debug($"Loading pedestrian light @ seg. {e.Key}, step {j}: "+
$"{cnfLights.pedestrianLightState} {cnfLights.manualPedestrianMode}");
#endif
lights.ManualPedestrianMode = cnfLights.manualPedestrianMode;
lights.PedestrianLightState = cnfLights.pedestrianLightState;
bool first = true; // v1.10.2 transitional code
foreach (KeyValuePair<ExtVehicleType, Configuration.CustomSegmentLight> e2
in cnfLights.customLights) {
#if DEBUGLOAD
Log._Debug($"Loading timed step {j}, segment {e.Key}, vehicleType "+
$"{e2.Key} at node {cnfTimedLights.nodeId}");
#endif
if (!lights.CustomLights.TryGetValue(
LegacyExtVehicleType.ToNew(e2.Key),
out ICustomSegmentLight light)) {
#if DEBUGLOAD
Log._Debug($"No segment light found for timed step {j}, segment "+
$"{e.Key}, vehicleType {e2.Key} at node {cnfTimedLights.nodeId}");
#endif
// v1.10.2 transitional code START
if (first) {
first = false;
if (!lights.CustomLights.TryGetValue(
CustomSegmentLights
.DEFAULT_MAIN_VEHICLETYPE,
out light)) {
#if DEBUGLOAD
Log._Debug($"No segment light found for timed step {j}, "+
$"segment {e.Key}, DEFAULT vehicleType {CustomSegmentLights.DEFAULT_MAIN_VEHICLETYPE} "+
$"at node {cnfTimedLights.nodeId}");
#endif
continue;
}
} else {
// v1.10.2 transitional code END
continue;
// v1.10.2 transitional code START
}
// v1.10.2 transitional code END
}
Configuration.CustomSegmentLight cnfLight = e2.Value;
light.InternalCurrentMode = (LightMode)cnfLight.currentMode; // TODO improve & remove
light.SetStates(
cnfLight.mainLight,
cnfLight.leftLight,
cnfLight.rightLight,
false);
}
}
++j;
}
} catch (Exception e) {
// ignore, as it's probably corrupt save data. it'll be culled on next save
Log.Warning($"Error loading data from TimedNode (new method): {e}");
success = false;
}
}
foreach (Configuration.TimedTrafficLights cnfTimedLights in data) {
try {
ITimedTrafficLights timedNode =
TrafficLightSimulations[cnfTimedLights.nodeId].timedLight;
timedNode.Housekeeping();
if (cnfTimedLights.started) {
timedNode.Start(cnfTimedLights.currentStep);
}
} catch (Exception e) {
Log.Warning($"Error starting timed light @ {cnfTimedLights.nodeId}: {e}");
success = false;
}
}
return success;
}
19
Source : AssetData.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
public static SegmentNetworkIDs [] GetPathsNetworkIDs(BuildingInfo prefab) {
// Code based on BuildingDecorations.SavePaths()
Building[] buildingBuffer = BuildingManager.instance.m_buildings.m_buffer;
List<ushort> replacedetSegmentIds = new List<ushort>();
List<ushort> buildingIds = new List<ushort>(prefab.m_paths.Length);
var ret = new List<SegmentNetworkIDs>();
for (ushort buildingId = 1; buildingId < BuildingManager.MAX_BUILDING_COUNT; buildingId += 1) {
if (buildingBuffer[buildingId].m_flags != Building.Flags.None) {
replacedetSegmentIds.AddRange(BuildingDecoration.GetBuildingSegments(ref buildingBuffer[buildingId]));
buildingIds.Add(buildingId);
}
}
ExtSegmentManager extSegmentManager = ExtSegmentManager.Instance;
for (ushort segmentId = 0; segmentId < NetManager.MAX_SEGMENT_COUNT; segmentId++) {
if (extSegmentManager.IsSegmentValid(segmentId)) {
if (!replacedetSegmentIds.Contains(segmentId)) {
ret.Add(new SegmentNetworkIDs(segmentId));
}
}
}
return ret.ToArray();
}
19
Source : AutoTimedTrafficLights.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
public static bool Add(ushort nodeId) {
List<ushort> nodeGroup = new List<ushort>(1);
nodeGroup.Add(nodeId);
return tlsMan.SetUpTimedTrafficLight(nodeId, nodeGroup);
}
19
Source : AutoTimedTrafficLights.cs
with MIT License
from CitiesSkylinesMods
with MIT License
from CitiesSkylinesMods
private static List<ushort> TwoWayRoads(List<ushort> segList, out int count) {
List<ushort> segList2 = new List<ushort>();
foreach(var segId in segList) {
if (!segMan.CalculateIsOneWay(segId)) {
segList2.Add(segId);
}
}
count = segList2.Count;
return segList2;
}
19
Source : MapImport.cs
with MIT License
from csinkers
with MIT License
from csinkers
static (IList<EventNode> events, IList<ushort> chains) BuildChains(MapId mapId, List<TriggerInfo> triggers, List<NpcInfo> npcs, replacedetMapping mapping)
{
var scriptables = triggers.Cast<IScriptable>().Concat(npcs);
foreach (var scriptable in scriptables)
BuildEventHash(mapId, scriptable, mapping);
var scripts = scriptables.GroupBy(x => x.Key, ScriptableKeyComparer.Instance);
var scriptsByHint = new Dictionary<ChainHint, List<IGrouping<ScriptableKey, IScriptable>>>();
foreach (var g in scripts)
{
foreach (var scriptable in g)
{
scriptable.EventBytes = g.Key.EventBytes;
var first = g.First();
if (scriptable != first && first.Events != null)
scriptable.Events = first.Events.ToList();
}
if (!scriptsByHint.TryGetValue(g.Key.ChainHint, out var group))
{
group = new List<IGrouping<ScriptableKey, IScriptable>>();
scriptsByHint[g.Key.ChainHint] = group;
}
group.Add(g);
}
var events = new List<EventNode>();
var chains = new List<ushort>();
ushort eventId = 0;
foreach (var kvp in scriptsByHint.OrderBy(x => x.Key))
{
var hint = kvp.Key;
var groupsWithHint = kvp.Value;
if (hint.IsNone)
continue;
if (hint.IsChain)
{
while (chains.Count <= hint.ChainId)
chains.Add(ushort.MaxValue);
chains[hint.ChainId] = eventId;
if (groupsWithHint.Count > 1)
{
// Map Map.TorontoStart contains multiple scriptable enreplacedies with differing event chains but the same chain hint (12):
// Version 1: 1, 4, 5
// Version 2: 3
var sb = new StringBuilder();
sb.AppendLine($"Map {mapId} contains multiple scriptable enreplacedies with differing event chains but the same chain hint ({hint}):");
int version = 1;
foreach (var grouping in groupsWithHint)
{
sb.Append("Version "); sb.Append(version++); sb.Append(": ");
foreach (var scriptable in grouping)
{
sb.Append(scriptable.ObjectId);
sb.Append(' ');
}
sb.AppendLine();
}
throw new FormatException(sb.ToString());
}
}
var groupEvents = groupsWithHint[0].First().Events;
foreach (var e in groupEvents)
{
events.Add(e);
e.Id = eventId;
eventId++;
}
}
if (scriptsByHint.TryGetValue(ChainHint.None, out var groupsWithoutHint))
{
var group = groupsWithoutHint[^1];
groupsWithoutHint.RemoveAt(groupsWithoutHint.Count - 1);
if (groupsWithoutHint.Count == 0)
scriptsByHint.Remove(ChainHint.None);
var groupEvents = group.First().Events;
if (groupEvents != null)
{
foreach (var e in groupEvents)
{
events.Add(e);
e.Id = eventId;
eventId++;
}
}
}
return (events, chains);
}
19
Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from Cuyler36
with GNU General Public License v2.0
from Cuyler36
private void Import_Click(object sender, RoutedEventArgs e)
{
if (SelectIconImageDialog.ShowDialog().Value && File.Exists(SelectIconImageDialog.FileName))
{
try
{
BitmapImage Img = new BitmapImage();
Img.BeginInit();
Img.UriSource = new Uri(SelectIconImageDialog.FileName);
Img.EndInit();
if (Img.PixelWidth == 32 && Img.PixelHeight == 32)
{
//IconImage.Source = Img;
// Get the image data
byte[] PixelData = new byte[4 * 32 * 32];
Img.CopyPixels(PixelData, 4 * 32, 0);
int[] ImageData = new int[32 * 32];
Buffer.BlockCopy(PixelData, 0, ImageData, 0, PixelData.Length);
// Convert it to C8 format
IconData = new byte[0x600];
List<ushort> PaletteList = new List<ushort>();
for (int i = 0, idx = 0; i < 32 * 32; i++, idx += 4)
{
ushort RGB5A3Color = RGB5A3.ToRGB5A3(PixelData[idx + 3], PixelData[idx + 2], PixelData[idx + 1], PixelData[idx]);
if (!PaletteList.Contains(RGB5A3Color))
{
PaletteList.Add(RGB5A3Color);
}
}
ushort[] Palette = PaletteList.ToArray();
if (Palette.Length > 256)
{
Array.Resize(ref Palette, 256);
}
C8.EncodeC8(ImageData, Palette, 32, 32).CopyTo(IconData, 0);
for (int i = 0; i < PaletteList.Count; i++)
{
BitConverter.GetBytes(PaletteList[i].Reverse()).CopyTo(IconData, 0x400 + i * 2);
}
// Refresh the Icon Image
RefreshIconImage();
}
else
{
MessageBox.Show("The icon you selected is not 32x32 pixels! Please resize it to that and try again.", "Icon Import Error", MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
catch
{
MessageBox.Show("The icon you selected could not be imported! Please try again.", "Icon Import Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
19
Source : Conversation.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
bool Create(ulong lowGuid, uint conversationEntry, Map map, Unit creator, Position pos, ObjectGuid privateObjectOwner, SpellInfo spellInfo = null)
{
ConversationTemplate conversationTemplate = Global.ConversationDataStorage.GetConversationTemplate(conversationEntry);
//replacedERT(conversationTemplate);
_creatorGuid = creator.GetGUID();
SetPrivateObjectOwner(privateObjectOwner);
SetMap(map);
Relocate(pos);
RelocateStationaryPosition(pos);
_Create(ObjectGuid.Create(HighGuid.Conversation, GetMapId(), conversationEntry, lowGuid));
PhasingHandler.InheritPhaseShift(this, creator);
SetEntry(conversationEntry);
SetObjectScale(1.0f);
_textureKitId = conversationTemplate.TextureKitId;
if (conversationTemplate.Actors != null)
{
foreach (var actor in conversationTemplate.Actors)
{
if (actor != null)
{
ConversationActorField actorField = new();
actorField.CreatureID = actor.CreatureId;
actorField.CreatureDisplayInfoID = actor.CreatureDisplayInfoId;
actorField.Id = (int)actor.ActorId;
actorField.Type = ConversationActorType.CreatureActor;
AddDynamicUpdateFieldValue(m_values.ModifyValue(m_conversationData).ModifyValue(m_conversationData.Actors), actorField);
}
}
}
if (conversationTemplate.ActorGuids != null)
{
for (ushort actorIndex = 0; actorIndex < conversationTemplate.ActorGuids.Count; ++actorIndex)
{
ulong actorGuid = conversationTemplate.ActorGuids[actorIndex];
if (actorGuid == 0)
continue;
foreach (var creature in map.GetCreatureBySpawnIdStore().LookupByKey(actorGuid))
{
// we just need the last one, overriding is legit
AddActor(creature.GetGUID(), actorIndex);
}
}
}
Global.ScriptMgr.OnConversationCreate(this, creator);
List<ushort> actorIndices = new();
List<ConversationLine> lines = new();
foreach (ConversationLineTemplate line in conversationTemplate.Lines)
{
if (!Global.ConditionMgr.IsObjectMeetingNotGroupedConditions(ConditionSourceType.ConversationLine, line.Id, creator))
continue;
actorIndices.Add(line.ActorIdx);
ConversationLine lineField = new();
lineField.ConversationLineID = line.Id;
lineField.UiCameraID = line.UiCameraID;
lineField.ActorIndex = line.ActorIdx;
lineField.Flags = line.Flags;
ConversationLineRecord convoLine = CliDB.ConversationLineStorage.LookupByKey(line.Id); // never null for conversationTemplate->Lines
for (Locale locale = Locale.enUS; locale < Locale.Total; locale = locale + 1)
{
if (locale == Locale.None)
continue;
_lineStartTimes[(locale, line.Id)] = _lastLineEndTimes[(int)locale];
if (locale == Locale.enUS)
lineField.StartTime = (uint)_lastLineEndTimes[(int)locale].TotalMilliseconds;
int broadcastTextDuration = Global.DB2Mgr.GetBroadcastTextDuration((int)convoLine.BroadcastTextID, locale);
if (broadcastTextDuration != 0)
_lastLineEndTimes[(int)locale] += TimeSpan.FromMilliseconds(broadcastTextDuration);
_lastLineEndTimes[(int)locale] += TimeSpan.FromMilliseconds(convoLine.AdditionalDuration);
}
lines.Add(lineField);
}
_duration = _lastLineEndTimes.Max();
SetUpdateFieldValue(m_values.ModifyValue(m_conversationData).ModifyValue(m_conversationData.LastLineEndTime), (uint)_duration.TotalMilliseconds);
SetUpdateFieldValue(m_values.ModifyValue(m_conversationData).ModifyValue(m_conversationData.Lines), lines);
// conversations are despawned 5-20s after LastLineEndTime
_duration += TimeSpan.FromSeconds(10);
Global.ScriptMgr.OnConversationCreate(this, creator);
// All actors need to be set
foreach (ushort actorIndex in actorIndices)
{
ConversationActorField actor = actorIndex < m_conversationData.Actors.Size() ? m_conversationData.Actors[actorIndex] : null;
if (actor == null || (actor.CreatureID == 0 && actor.ActorGUID.IsEmpty() && actor.NoActorObject == 0))
{
Log.outError(LogFilter.Conversation, $"Failed to create conversation (Id: {conversationEntry}) due to missing actor (Idx: {actorIndex}).");
return false;
}
}
if (!GetMap().AddToMap(this))
return false;
return true;
}
19
Source : WardenWin.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public override void RequestData()
{
Log.outDebug(LogFilter.Warden, "Request data");
// If all checks were done, fill the todo list again
if (_memChecksTodo.Empty())
_memChecksTodo.AddRange(Global.WardenCheckMgr.MemChecksIdPool);
if (_otherChecksTodo.Empty())
_otherChecksTodo.AddRange(Global.WardenCheckMgr.OtherChecksIdPool);
_serverTicks = GameTime.GetGameTimeMS();
ushort id;
WardenCheckType type;
WardenCheck wd;
_currentChecks.Clear();
// Build check request
for (uint i = 0; i < WorldConfig.GetUIntValue(WorldCfg.WardenNumMemChecks); ++i)
{
// If todo list is done break loop (will be filled on next Update() run)
if (_memChecksTodo.Empty())
break;
// Get check id from the end and remove it from todo
id = _memChecksTodo.Last();
_memChecksTodo.Remove(id);
// Add the id to the list sent in this cycle
_currentChecks.Add(id);
}
ByteBuffer buffer = new();
buffer.WriteUInt8((byte)WardenOpcodes.Smsg_CheatChecksRequest);
for (uint i = 0; i < WorldConfig.GetUIntValue(WorldCfg.WardenNumOtherChecks); ++i)
{
// If todo list is done break loop (will be filled on next Update() run)
if (_otherChecksTodo.Empty())
break;
// Get check id from the end and remove it from todo
id = _otherChecksTodo.Last();
_otherChecksTodo.Remove(id);
// Add the id to the list sent in this cycle
_currentChecks.Add(id);
wd = Global.WardenCheckMgr.GetWardenDataById(id);
switch (wd.Type)
{
case WardenCheckType.MPQ:
case WardenCheckType.LuaStr:
case WardenCheckType.Driver:
buffer.WriteUInt8((byte)wd.Str.GetByteCount());
buffer.WriteString(wd.Str);
break;
default:
break;
}
}
byte xorByte = _inputKey[0];
// Add TIMING_CHECK
buffer.WriteUInt8(0x00);
buffer.WriteUInt8((byte)((int)WardenCheckType.Timing ^ xorByte));
byte index = 1;
foreach (var checkId in _currentChecks)
{
wd = Global.WardenCheckMgr.GetWardenDataById(checkId);
type = wd.Type;
buffer.WriteUInt8((byte)((int)type ^ xorByte));
switch (type)
{
case WardenCheckType.Memory:
{
buffer.WriteUInt8(0x00);
buffer.WriteUInt32(wd.Address);
buffer.WriteUInt8(wd.Length);
break;
}
case WardenCheckType.PageA:
case WardenCheckType.PageB:
{
buffer.WriteBytes(wd.Data.ToByteArray());
buffer.WriteUInt32(wd.Address);
buffer.WriteUInt8(wd.Length);
break;
}
case WardenCheckType.MPQ:
case WardenCheckType.LuaStr:
{
buffer.WriteUInt8(index++);
break;
}
case WardenCheckType.Driver:
{
buffer.WriteBytes(wd.Data.ToByteArray());
buffer.WriteUInt8(index++);
break;
}
case WardenCheckType.Module:
{
uint seed = RandomHelper.Rand32();
buffer.WriteUInt32(seed);
HmacHash hmac = new(BitConverter.GetBytes(seed));
hmac.Finish(wd.Str);
buffer.WriteBytes(hmac.Digest);
break;
}
/*case PROC_CHECK:
{
buff.append(wd.i.AsByteArray(0, false).get(), wd.i.GetNumBytes());
buff << uint8(index++);
buff << uint8(index++);
buff << uint32(wd.Address);
buff << uint8(wd.Length);
break;
}*/
default:
break; // Should never happen
}
}
buffer.WriteUInt8(xorByte);
Warden3DataServer packet = new();
packet.Data = EncryptData(buffer.GetData());
_session.SendPacket(packet);
_dataSent = true;
string stream = "Sent check id's: ";
foreach (var checkId in _currentChecks)
stream += checkId + " ";
Log.outDebug(LogFilter.Warden, stream);
}
19
Source : WardenCheckManager.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public void LoadWardenChecks()
{
uint oldMSTime = Time.GetMSTime();
// Check if Warden is enabled by config before loading anything
if (!WorldConfig.GetBoolValue(WorldCfg.WardenEnabled))
{
Log.outInfo(LogFilter.Warden, "Warden disabled, loading checks skipped.");
return;
}
// 0 1 2 3 4 5 6 7
SQLResult result = DB.World.Query("SELECT id, type, data, result, address, length, str, comment FROM warden_checks ORDER BY id ASC");
if (result.IsEmpty())
{
Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Warden checks. DB table `warden_checks` is empty!");
return;
}
uint count = 0;
do
{
ushort id = result.Read<ushort>(0);
WardenCheckType checkType = (WardenCheckType)result.Read<byte>(1);
string data = result.Read<string>(2);
string checkResult = result.Read<string>(3);
uint address = result.Read<uint>(4);
byte length = result.Read<byte>(5);
string str = result.Read<string>(6);
string comment = result.Read<string>(7);
WardenCheck wardenCheck = new();
wardenCheck.Type = checkType;
wardenCheck.CheckId = id;
// Initialize action with default action from config
wardenCheck.Action = (WardenActions)WorldConfig.GetIntValue(WorldCfg.WardenClientFailAction);
if (checkType == WardenCheckType.PageA || checkType == WardenCheckType.PageB || checkType == WardenCheckType.Driver)
wardenCheck.Data = new BigInteger(data.ToByteArray());
if (checkType == WardenCheckType.Memory || checkType == WardenCheckType.Module)
MemChecksIdPool.Add(id);
else
OtherChecksIdPool.Add(id);
if (checkType == WardenCheckType.Memory || checkType == WardenCheckType.PageA || checkType == WardenCheckType.PageB || checkType == WardenCheckType.Proc)
{
wardenCheck.Address = address;
wardenCheck.Length = length;
}
// PROC_CHECK support missing
if (checkType == WardenCheckType.Memory || checkType == WardenCheckType.MPQ || checkType == WardenCheckType.LuaStr || checkType == WardenCheckType.Driver || checkType == WardenCheckType.Module)
wardenCheck.Str = str;
CheckStore[id] = wardenCheck;
if (checkType == WardenCheckType.MPQ || checkType == WardenCheckType.Memory)
{
BigInteger Result = new(checkResult.ToByteArray());
CheckResultStore[id] = Result;
}
if (comment.IsEmpty())
wardenCheck.Comment = "Undoreplacedented Check";
else
wardenCheck.Comment = comment;
++count;
}
while (result.NextRow());
Log.outInfo(LogFilter.ServerLoading, $"Loaded {count} warden checks in {Time.GetMSTimeDiffToNow(oldMSTime)} ms");
}
19
Source : TerrainBuilder.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public void loadOffMeshConnections(uint mapID, uint tileX, uint tileY, MeshData meshData, string offMeshFilePath)
{
// no meshfile input given?
if (offMeshFilePath == null)
return;
if (!File.Exists(offMeshFilePath))
{
Console.WriteLine($"loadOffMeshConnections: input file {offMeshFilePath} not found!");
return;
}
using BinaryReader binaryReader = new(File.Open(offMeshFilePath, FileMode.Open, FileAccess.Read, FileShare.Read));
// pretty silly thing, as we parse entire file and load only the tile we need
// but we don't expect this file to be too large
long fileLength = binaryReader.BaseStream.Length;
while (binaryReader.BaseStream.Position < fileLength)
{
var s = binaryReader.ReadString(512);
float[] p0 = new float[0];
float[] p1 = new float[0];
uint mid = 0, tx = 0, ty = 0;
float size = 0;
string[] stringValues = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in stringValues)
{
}
if (mapID == mid && tileX == tx && tileY == ty)
{
meshData.offMeshConnections.Add(p0[1]);
meshData.offMeshConnections.Add(p0[2]);
meshData.offMeshConnections.Add(p0[0]);
meshData.offMeshConnections.Add(p1[1]);
meshData.offMeshConnections.Add(p1[2]);
meshData.offMeshConnections.Add(p1[0]);
meshData.offMeshConnectionDirs.Add(1); // 1 - both direction, 0 - one sided
meshData.offMeshConnectionRads.Add(size); // agent size equivalent
// can be used same way as polygon flags
meshData.offMeshConnectionsAreas.Add(0xFF);
meshData.offMeshConnectionsFlags.Add(0xFF); // all movement masks can make this path
}
}
}
19
Source : Wmo.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public bool Open(uint fileId, WMORoot rootWmo)
{
Stream stream = Program.CascHandler.OpenFile((int)fileId);
if (stream == null)
{
Console.WriteLine("No such file.");
return false;
}
using (BinaryReader reader = new(stream))
{
long fileLength = reader.BaseStream.Length;
while (reader.BaseStream.Position < fileLength)
{
string fourcc = reader.ReadStringFromChars(4, true);
uint size = reader.ReadUInt32();
if (fourcc == "MOGP")//Fix sizeoff = Data size.
size = 68;
long nextpos = reader.BaseStream.Position + size;
if (fourcc == "MOGP")//header
{
groupName = reader.ReadInt32();
descGroupName = reader.ReadInt32();
mogpFlags = reader.ReadInt32();
for (var i = 0; i < 3; ++i)
bbcorn1[i] = reader.ReadSingle();
for (var i = 0; i < 3; ++i)
bbcorn2[i] = reader.ReadSingle();
moprIdx = reader.ReadUInt16();
moprNItems = reader.ReadUInt16();
nBatchA = reader.ReadUInt16();
nBatchB = reader.ReadUInt16();
nBatchC = reader.ReadUInt32();
fogIdx = reader.ReadUInt32();
groupLiquid = reader.ReadUInt32();
groupWMOID = reader.ReadUInt32();
// according to WoW.Dev Wiki:
if (Convert.ToBoolean(rootWmo.flags & 4))
groupLiquid = GetLiquidTypeId(groupLiquid);
else if (groupLiquid == 15)
groupLiquid = 0;
else
groupLiquid = GetLiquidTypeId(groupLiquid + 1);
if (groupLiquid != 0)
liquflags |= 2;
}
else if (fourcc == "MOPY")
{
mopy_size = (int)size;
nTriangles = (int)size / 2;
MOPY = reader.ReadString((int)size);
}
else if (fourcc == "MOVI")
{
MOVI = new ushort[size / 2];
for (var i = 0; i < size / 2; ++i)
MOVI[i] = reader.ReadUInt16();
}
else if (fourcc == "MOVT")
{
MOVT = new float[size / 4];
for (var i = 0; i < size / 4; ++i)
MOVT[i] = reader.ReadSingle();
nVertices = size / 12;
}
else if (fourcc == "MONR")
{
}
else if (fourcc == "MOTV")
{
}
else if (fourcc == "MOBA")
{
MOBA = new ushort[size / 2];
moba_size = (int)(size / 2);
for (var i = 0; i < size / 2; ++i)
MOBA[i] = reader.ReadUInt16();
}
else if (fourcc == "MODR")
{
for (var i = 0; i < size / 2; ++i)
DoodadReferences.Add(reader.Read<ushort>());
}
else if (fourcc == "MLIQ")
{
liquflags |= 1;
hlq = reader.Read<WMOLiquidHeader>();
LiquEx_size = 8 * hlq.xverts * hlq.yverts;
LiquEx = new WMOLiquidVert[hlq.xverts * hlq.yverts];
for (var i = 0; i < hlq.xverts * hlq.yverts; ++i)
LiquEx[i] = reader.Read<WMOLiquidVert>();
int nLiquBytes = hlq.xtiles * hlq.ytiles;
LiquBytes = reader.ReadBytes(nLiquBytes);
// Determine legacy liquid type
if (groupLiquid == 0)
{
for (int i = 0; i < hlq.xtiles * hlq.ytiles; ++i)
{
if ((LiquBytes[i] & 0xF) != 15)
{
groupLiquid = GetLiquidTypeId((uint)(LiquBytes[i] & 0xF) + 1);
break;
}
}
}
/* std::ofstream llog("Buildings/liquid.log", ios_base::out | ios_base::app);
llog << filename;
llog << "\nbbox: " << bbcorn1[0] << ", " << bbcorn1[1] << ", " << bbcorn1[2] << " | " << bbcorn2[0] << ", " << bbcorn2[1] << ", " << bbcorn2[2];
llog << "\nlpos: " << hlq->pos_x << ", " << hlq->pos_y << ", " << hlq->pos_z;
llog << "\nx-/yvert: " << hlq->xverts << "/" << hlq->yverts << " size: " << size << " expected size: " << 30 + hlq->xverts*hlq->yverts*8 + hlq->xtiles*hlq->ytiles << std::endl;
llog.close(); */
}
reader.BaseStream.Seek((int)nextpos, SeekOrigin.Begin);
}
}
return true;
}
19
Source : EMFloorFunction.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
private void GenerateOverlaps(TR2Level level, ushort currentBoxIndex, ushort newBoxIndex)
{
for (int i = 0; i < level.NumBoxes; i++)
{
TR2Box box = level.Boxes[i];
// Anything that has the current box as an overlap will need
// to also have the new box, or if this is the current box, it
// will need the new box linked to it.
List<ushort> overlaps = TR2BoxUtilities.GetOverlaps(level, box);
if (overlaps.Contains(currentBoxIndex) || i == currentBoxIndex)
{
// Add the new index and write it back
overlaps.Add(newBoxIndex);
TR2BoxUtilities.UpdateOverlaps(level, box, overlaps);
}
}
}
19
Source : TR2BoxUtilities.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
private static void UpdateOverlaps(TR2Box lvlBox, List<ushort> boxOverlaps, List<ushort> newOverlaps, short noOverlap)
{
// Either append the current overlaps, or the new ones if this is the box being updated.
// Do nothing for boxes that have no overlaps.
if (boxOverlaps.Count > 0)
{
// TR2 uses -1 as NoOverlap, but TR3+ uses 2047. So we can never use 2047
// as an index itself. Add a dummy entry, which will never be referenced.
if (newOverlaps.Count == noOverlap)
{
newOverlaps.Add(0);
}
// Mark the overlap offset for this box to the insertion point
UpdateOverlapIndex(lvlBox, newOverlaps.Count);
for (int i = 0; i < boxOverlaps.Count; i++)
{
ushort index = boxOverlaps[i];
if (i == boxOverlaps.Count - 1)
{
// Make sure the final overlap has the end bit set.
index |= EndBit;
}
newOverlaps.Add(index);
}
}
}
19
Source : EMCopyRoomFunction.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
public override void ApplyToLevel(TR3Level level)
{
TR3Room baseRoom = level.Rooms[RoomIndex];
int xdiff = NewLocation.X - baseRoom.Info.X;
int ydiff = NewLocation.Y - baseRoom.Info.YBottom;
int zdiff = NewLocation.Z - baseRoom.Info.Z;
TR3Room newRoom = new TR3Room
{
AlternateRoom = -1,
AmbientIntensity = baseRoom.AmbientIntensity,
Filler = baseRoom.Filler,
Flags = baseRoom.Flags,
Info = new TRRoomInfo
{
X = NewLocation.X,
YBottom = NewLocation.Y,
YTop = NewLocation.Y + (baseRoom.Info.YTop - baseRoom.Info.YBottom),
Z = NewLocation.Z
},
Lights = new TR3RoomLight[baseRoom.NumLights],
LightMode = baseRoom.LightMode,
NumDataWords = baseRoom.NumDataWords,
NumLights = baseRoom.NumLights,
NumPortals = 0,
NumStaticMeshes = baseRoom.NumStaticMeshes,
NumXSectors = baseRoom.NumXSectors,
NumZSectors = baseRoom.NumZSectors,
Portals = new TRRoomPortal[] { },
ReverbInfo = baseRoom.ReverbInfo,
RoomData = new TR3RoomData
{
NumRectangles = baseRoom.RoomData.NumRectangles,
NumSprites = baseRoom.RoomData.NumSprites,
NumTriangles = baseRoom.RoomData.NumTriangles,
NumVertices = baseRoom.RoomData.NumVertices,
Rectangles = new TRFace4[baseRoom.RoomData.NumRectangles],
Sprites = new TRRoomSprite[baseRoom.RoomData.NumSprites],
Triangles = new TRFace3[baseRoom.RoomData.NumTriangles],
Vertices = new TR3RoomVertex[baseRoom.RoomData.NumVertices]
},
Sectors = new TRRoomSector[baseRoom.Sectors.Length],
StaticMeshes = new TR3RoomStaticMesh[baseRoom.NumStaticMeshes],
WaterScheme = baseRoom.WaterScheme
};
// Lights
for (int i = 0; i < newRoom.Lights.Length; i++)
{
newRoom.Lights[i] = new TR3RoomLight
{
Colour = baseRoom.Lights[i].Colour,
LightProperties = baseRoom.Lights[i].LightProperties,
LightType = baseRoom.Lights[i].LightType,
X = baseRoom.Lights[i].X + xdiff,
Y = baseRoom.Lights[i].Y + ydiff,
Z = baseRoom.Lights[i].Z + zdiff
};
}
// Faces
for (int i = 0; i < newRoom.RoomData.NumRectangles; i++)
{
newRoom.RoomData.Rectangles[i] = new TRFace4
{
Texture = baseRoom.RoomData.Rectangles[i].Texture,
Vertices = new ushort[baseRoom.RoomData.Rectangles[i].Vertices.Length]
};
for (int j = 0; j < newRoom.RoomData.Rectangles[i].Vertices.Length; j++)
{
newRoom.RoomData.Rectangles[i].Vertices[j] = baseRoom.RoomData.Rectangles[i].Vertices[j];
}
}
for (int i = 0; i < newRoom.RoomData.NumTriangles; i++)
{
newRoom.RoomData.Triangles[i] = new TRFace3
{
Texture = baseRoom.RoomData.Triangles[i].Texture,
Vertices = new ushort[baseRoom.RoomData.Triangles[i].Vertices.Length]
};
for (int j = 0; j < newRoom.RoomData.Triangles[i].Vertices.Length; j++)
{
newRoom.RoomData.Triangles[i].Vertices[j] = baseRoom.RoomData.Triangles[i].Vertices[j];
}
}
// Vertices
for (int i = 0; i < newRoom.RoomData.Vertices.Length; i++)
{
newRoom.RoomData.Vertices[i] = new TR3RoomVertex
{
Attributes = baseRoom.RoomData.Vertices[i].Attributes,
Colour = baseRoom.RoomData.Vertices[i].Colour,
Lighting = baseRoom.RoomData.Vertices[i].Lighting,
Vertex = new TRVertex
{
X = baseRoom.RoomData.Vertices[i].Vertex.X, // Room coords for X and Z
Y = (short)(baseRoom.RoomData.Vertices[i].Vertex.Y + ydiff),
Z = baseRoom.RoomData.Vertices[i].Vertex.Z
}
};
}
// Sprites
for (int i = 0; i < newRoom.RoomData.NumSprites; i++)
{
newRoom.RoomData.Sprites[i] = new TRRoomSprite
{
Texture = baseRoom.RoomData.Sprites[i].Texture,
Vertex = baseRoom.RoomData.Sprites[i].Vertex
};
}
// Static Meshes
for (int i = 0; i < newRoom.NumStaticMeshes; i++)
{
newRoom.StaticMeshes[i] = new TR3RoomStaticMesh
{
Colour = baseRoom.StaticMeshes[i].Colour,
MeshID = baseRoom.StaticMeshes[i].MeshID,
Rotation = baseRoom.StaticMeshes[i].Rotation,
Unused = baseRoom.StaticMeshes[i].Unused,
X = (uint)(baseRoom.StaticMeshes[i].X + xdiff),
Y = (uint)(baseRoom.StaticMeshes[i].Y + ydiff),
Z = (uint)(baseRoom.StaticMeshes[i].Z + zdiff)
};
}
// Boxes, zones and sectors
FDControl floorData = new FDControl();
floorData.ParseFromLevel(level);
TRRoomSector linkedSector = FDUtilities.GetRoomSector(LinkedLocation.X, LinkedLocation.Y, LinkedLocation.Z, (short)ConverreplacedemNumber(LinkedLocation.Room, level.NumRooms), level, floorData);
ushort newBoxIndex = (ushort)level.NumBoxes;
int linkedBoxIndex = (linkedSector.BoxIndex & 0x7FF0) >> 4;
int linkedMaterial = linkedSector.BoxIndex & 0x000F; // TR3-5 store material in bits 0-3 - wood, mud etc
// Duplicate the zone for the new box and link the current box to the new room
TR2BoxUtilities.DuplicateZone(level, linkedBoxIndex);
TR2Box linkedBox = level.Boxes[linkedBoxIndex];
List<ushort> overlaps = TR2BoxUtilities.GetOverlaps(level, linkedBox);
overlaps.Add(newBoxIndex);
TR2BoxUtilities.UpdateOverlaps(level, linkedBox, overlaps);
// Make a new box for the new room
byte xmin = (byte)(newRoom.Info.X / SectorSize);
byte zmin = (byte)(newRoom.Info.Z / SectorSize);
byte xmax = (byte)((newRoom.Info.X / SectorSize) + (newRoom.Sectors.Length / newRoom.NumZSectors));
byte zmax = (byte)((newRoom.Info.Z / SectorSize) + (newRoom.Sectors.Length % newRoom.NumZSectors));
TR2Box box = new TR2Box
{
XMin = xmin,
ZMin = zmin,
XMax = xmax,
ZMax = zmax,
TrueFloor = (short)newRoom.Info.YBottom
};
List<TR2Box> boxes = level.Boxes.ToList();
boxes.Add(box);
level.Boxes = boxes.ToArray();
level.NumBoxes++;
// Link the box to the room we're joining to
TR2BoxUtilities.UpdateOverlaps(level, box, new List<ushort> { (ushort)linkedBoxIndex });
// Now update each of the sectors in the new room. The box index in each sector
// needs to reference the material so pack this into the box index.
newBoxIndex <<= 4;
newBoxIndex |= (ushort)linkedMaterial;
for (int i = 0; i < newRoom.Sectors.Length; i++)
{
int sectorYDiff = 0;
ushort sectorBoxIndex = baseRoom.Sectors[i].BoxIndex;
// Only change the sector if it's not impenetrable
if (baseRoom.Sectors[i].Ceiling != _solidSector || baseRoom.Sectors[i].Floor != _solidSector)
{
sectorYDiff = ydiff / ClickSize;
sectorBoxIndex = newBoxIndex;
}
newRoom.Sectors[i] = new TRRoomSector
{
BoxIndex = sectorBoxIndex,
Ceiling = (sbyte)(baseRoom.Sectors[i].Ceiling + sectorYDiff),
FDIndex = 0, // Initialise to no FD
Floor = (sbyte)(baseRoom.Sectors[i].Floor + sectorYDiff),
RoomAbove = _noRoom,
RoomBelow = _noRoom
};
// Duplicate the FD too for everything except triggers. Track any portals
// so they can be blocked off.
if (baseRoom.Sectors[i].FDIndex != 0)
{
List<FDEntry> entries = floorData.Entries[baseRoom.Sectors[i].FDIndex];
List<FDEntry> newEntries = new List<FDEntry>();
foreach (FDEntry entry in entries)
{
switch ((FDFunctions)entry.Setup.Function)
{
case FDFunctions.PortalSector:
// This portal will no longer be valid in the new room's position,
// so block off the wall
newRoom.Sectors[i].Floor = newRoom.Sectors[i].Ceiling = _solidSector;
break;
case FDFunctions.FloorSlant:
FDSlantEntry slantEntry = entry as FDSlantEntry;
newEntries.Add(new FDSlantEntry()
{
Setup = new FDSetup() { Value = slantEntry.Setup.Value },
SlantValue = slantEntry.SlantValue,
Type = FDSlantEntryType.FloorSlant
});
break;
case FDFunctions.CeilingSlant:
FDSlantEntry ceilingSlant = entry as FDSlantEntry;
newEntries.Add(new FDSlantEntry()
{
Setup = new FDSetup() { Value = ceilingSlant.Setup.Value },
SlantValue = ceilingSlant.SlantValue,
Type = FDSlantEntryType.CeilingSlant
});
break;
case FDFunctions.KillLara:
newEntries.Add(new FDKillLaraEntry()
{
Setup = new FDSetup() { Value = entry.Setup.Value }
});
break;
case FDFunctions.ClimbableWalls:
newEntries.Add(new FDClimbEntry()
{
Setup = new FDSetup() { Value = entry.Setup.Value }
});
break;
case FDFunctions.FloorTriangulationNWSE_Solid:
case FDFunctions.FloorTriangulationNESW_Solid:
case FDFunctions.CeilingTriangulationNW_Solid:
case FDFunctions.CeilingTriangulationNE_Solid:
case FDFunctions.FloorTriangulationNWSE_SW:
case FDFunctions.FloorTriangulationNWSE_NE:
case FDFunctions.FloorTriangulationNESW_SW:
case FDFunctions.FloorTriangulationNESW_NW:
case FDFunctions.CeilingTriangulationNW_SW:
case FDFunctions.CeilingTriangulationNW_NE:
case FDFunctions.CeilingTriangulationNE_NW:
case FDFunctions.CeilingTriangulationNE_SE:
TR3TriangulationEntry triEntry = entry as TR3TriangulationEntry;
newEntries.Add(new TR3TriangulationEntry
{
Setup = new FDSetup { Value = triEntry.Setup.Value },
TriData = new FDTriangulationData { Value = triEntry.TriData.Value }
});
break;
case FDFunctions.Monkeyswing:
newEntries.Add(new TR3MonkeySwingEntry()
{
Setup = new FDSetup() { Value = entry.Setup.Value }
});
break;
case FDFunctions.DeferredTriggeringOrMinecartRotateLeft:
newEntries.Add(new TR3MinecartRotateLeftEntry()
{
Setup = new FDSetup() { Value = entry.Setup.Value }
});
break;
case FDFunctions.MechBeetleOrMinecartRotateRight:
newEntries.Add(new TR3MinecartRotateRightEntry()
{
Setup = new FDSetup() { Value = entry.Setup.Value }
});
break;
}
}
if (newEntries.Count > 0)
{
floorData.CreateFloorData(newRoom.Sectors[i]);
floorData.Entries[newRoom.Sectors[i].FDIndex].AddRange(newEntries);
}
}
}
floorData.WriteToLevel(level);
List<TR3Room> rooms = level.Rooms.ToList();
rooms.Add(newRoom);
level.Rooms = rooms.ToArray();
level.NumRooms++;
}
19
Source : EMFloorFunction.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
private void MoveFloor(TR2Level level)
{
// Find the vertices of the current floor for the tile at the given location, create 4 additional
// vertices on top and make new TRFace4 entries for the sides so the platform isn't floating.
// TODO: how to handle raising/lowering slants, all of this replacedumes a flat floor to begin with.
int clickChange = Clicks * ClickSize;
FDControl fdc = new FDControl();
fdc.ParseFromLevel(level);
short roomNumber = (short)ConverreplacedemNumber(Location.Room, level.NumRooms);
TR2Room room = level.Rooms[roomNumber];
TRRoomSector sector = FDUtilities.GetRoomSector(Location.X, Location.Y, Location.Z, roomNumber, level, fdc);
int sectorIndex = room.SectorList.ToList().IndexOf(sector);
// Find the current vertices for this tile
short x = (short)(sectorIndex / room.NumZSectors * SectorSize);
short z = (short)(sectorIndex % room.NumZSectors * SectorSize);
short y = (short)(sector.Floor * ClickSize);
List<TR2RoomVertex> vertices = room.RoomData.Vertices.ToList();
List<ushort> oldVertIndices = new List<ushort>();
List<TRVertex> defVerts = GetTileVertices(x, y, z, false);
// Check the Y vals are unanimous because we currently only support raising/lowering flat surfaces
if (!defVerts.All(v => v.Y == defVerts[0].Y))
{
throw new NotImplementedException("Floor manipulation is limited to flat surfaces only.");
}
for (int i = 0; i < defVerts.Count; i++)
{
TRVertex vert = defVerts[i];
int vi = vertices.FindIndex(v => v.Vertex.X == vert.X && v.Vertex.Z == vert.Z && v.Vertex.Y == vert.Y);
if (vi != -1)
{
oldVertIndices.Add((ushort)vi);
}
}
// Create new vertices - we can't just change the original vertex Y vals as adjoining tiles also use
// those and we need the originals for the new sides to this platform.
List<ushort> newVertIndices = new List<ushort>();
foreach (ushort vert in oldVertIndices)
{
TR2RoomVertex oldRoomVertex = vertices[vert];
TRVertex oldVert = vertices[vert].Vertex;
TRVertex newVertex = new TRVertex
{
X = oldVert.X,
Y = (short)(oldVert.Y + clickChange),
Z = oldVert.Z
};
newVertIndices.Add((ushort)CreateRoomVertex(room, newVertex, oldRoomVertex.Lighting, oldRoomVertex.Lighting2));
}
// Refresh
vertices = room.RoomData.Vertices.ToList();
// Get the tile face that matches the vertex list
List<TRFace4> rectangles = room.RoomData.Rectangles.ToList();
TRFace4 floorFace = rectangles.Find(r => r.Vertices.ToList().All(oldVertIndices.Contains));
// If the floor has been lowered (remember +Clicks = move down, -Clicks = move up)
// then the sides will also need lowering.
if (Clicks > 0)
{
// Find faces that share 2 of the old vertices
int floorY = room.RoomData.Vertices[floorFace.Vertices[0]].Vertex.Y;
foreach (TRFace4 face in rectangles)
{
if (face == floorFace)
{
continue;
}
List<ushort> faceVerts = face.Vertices.ToList();
List<ushort> sharedVerts = faceVerts.Where(oldVertIndices.Contains).ToList();
List<ushort> uniqueVerts = faceVerts.Except(sharedVerts).ToList();
if (sharedVerts.Count == 2 && uniqueVerts.Count == 2)
{
foreach (ushort sharedVert in sharedVerts)
{
int i = faceVerts.IndexOf(sharedVert);
TRVertex oldVert = vertices[sharedVert].Vertex;
foreach (ushort newVert in newVertIndices)
{
TRVertex newVertex = vertices[newVert].Vertex;
if (newVertex.X == oldVert.X && newVertex.Z == oldVert.Z)
{
faceVerts[i] = newVert;
}
}
}
face.Vertices = faceVerts.ToArray();
}
}
}
// Now change the floor face's vertices, and its texture provided we want to.
if (floorFace != null && !RetainOriginalFloor)
{
floorFace.Vertices = newVertIndices.ToArray();
if (FloorTexture != ushort.MaxValue)
{
floorFace.Texture = FloorTexture;
}
}
// Make faces for the new platform's sides if we have clicked up, again provided we want to.
if (Clicks < 0 && SideTexture != ushort.MaxValue)
{
for (int i = 0; i < 4; i++)
{
// Only texture this side if it's set in the flags
if (((1 << i) & Flags) > 0)
{
int j = i == 3 ? 0 : (i + 1);
rectangles.Add(new TRFace4
{
Texture = SideTexture,
Vertices = new ushort[]
{
newVertIndices[j],
newVertIndices[i],
oldVertIndices[i],
oldVertIndices[j]
}
});
}
}
}
// Save the new faces
room.RoomData.Rectangles = rectangles.ToArray();
room.RoomData.NumRectangles = (short)rectangles.Count;
// Account for the added faces
room.NumDataWords = (uint)(room.RoomData.Serialize().Length / 2);
// Now shift the actual sector info and adjust the box if necessary
sector.Floor += Clicks;
AlterSectorBox(level, room, sectorIndex);
// Move any enreplacedies that share the same floor sector up or down the relevant number of clicks
foreach (TR2Enreplacedy enreplacedy in level.Enreplacedies)
{
if (enreplacedy.Room == roomNumber)
{
TRRoomSector enreplacedySector = FDUtilities.GetRoomSector(enreplacedy.X, enreplacedy.Y, enreplacedy.Z, enreplacedy.Room, level, fdc);
if (enreplacedySector == sector)
{
enreplacedy.Y += clickChange;
}
}
}
}
19
Source : FDTriggerEntry.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
public override ushort[] Flatten()
{
//FD Setup followed by TrigSetup
List<ushort> dataArray = new List<ushort>
{
Setup.Value,
TrigSetup.Value
};
//If key or switch, next uint16 will be ref to key or switch ent
if (TrigType == FDTrigType.Switch || TrigType == FDTrigType.Key)
dataArray.Add(SwitchOrKeyRef);
for (int i = 0; i < TrigActionList.Count; i++)
{
FDActionLisreplacedem action = TrigActionList[i];
// Ensure Continue is set on all but the final action, unless it's a camera action,
// in which case the CamAction will have Continue set to false if this is the final action.
action.Continue = (action.TrigAction == FDTrigAction.Camera || action.TrigAction == FDTrigAction.Flyby) || i < TrigActionList.Count - 1;
//For each action, record the value.
dataArray.Add(action.Value);
//If it is a camera action, record the additional camera action
if (action.TrigAction == FDTrigAction.Camera || action.TrigAction == FDTrigAction.Flyby)
{
action.CamAction.Continue = i < TrigActionList.Count - 1;
dataArray.Add(action.CamAction.Value);
}
}
//Return uint16 array
return dataArray.ToArray();
}
19
Source : FDTriggerEntry.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
public override ushort[] Flatten()
{
//FD Setup followed by TrigSetup
List<ushort> dataArray = new List<ushort>
{
Setup.Value,
TrigSetup.Value
};
//If key or switch, next uint16 will be ref to key or switch ent
if (TrigType == FDTrigType.Switch || TrigType == FDTrigType.Key)
dataArray.Add(SwitchOrKeyRef);
for (int i = 0; i < TrigActionList.Count; i++)
{
FDActionLisreplacedem action = TrigActionList[i];
// Ensure Continue is set on all but the final action, unless it's a camera action,
// in which case the CamAction will have Continue set to false if this is the final action.
action.Continue = (action.TrigAction == FDTrigAction.Camera || action.TrigAction == FDTrigAction.Flyby) || i < TrigActionList.Count - 1;
//For each action, record the value.
dataArray.Add(action.Value);
//If it is a camera action, record the additional camera action
if (action.TrigAction == FDTrigAction.Camera || action.TrigAction == FDTrigAction.Flyby)
{
action.CamAction.Continue = i < TrigActionList.Count - 1;
dataArray.Add(action.CamAction.Value);
}
}
//Return uint16 array
return dataArray.ToArray();
}
19
Source : EMHorizontalCollisionalPortalFunction.cs
with MIT License
from DanzaG
with MIT License
from DanzaG
public override void ApplyToLevel(TR3Level level)
{
FDControl control = new FDControl();
control.ParseFromLevel(level);
Dictionary<TRRoomSector, List<ushort>> sectorMap = new Dictionary<TRRoomSector, List<ushort>>();
foreach (short fromRoomNumber in Portals.Keys)
{
int convertedFromRoomNumber = ConverreplacedemNumber(fromRoomNumber, level.NumRooms);
foreach (short toRoomNumber in Portals[fromRoomNumber].Keys)
{
int convertedToRoomNumber = ConverreplacedemNumber(toRoomNumber, level.NumRooms);
foreach (EMLocation sectorLocation in Portals[fromRoomNumber][toRoomNumber])
{
TRRoomSector sector = FDUtilities.GetRoomSector(sectorLocation.X, sectorLocation.Y, sectorLocation.Z, (short)convertedFromRoomNumber, level, control);
if (!sectorMap.ContainsKey(sector))
{
sectorMap[sector] = new List<ushort>();
}
sectorMap[sector].Add((ushort)convertedToRoomNumber);
}
}
}
CreatePortals(sectorMap, control);
control.WriteToLevel(level);
}
See More Examples