Here are the examples of the csharp api System.Collections.Generic.List.Add(short) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
95 Examples
19
View Source File : Formatter.Array1.List.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public List<Int16> Deserialize(ref BssomReader reader, ref BssomDeserializeContext context)
{
if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int16Code))
{
return default;
}
context.Option.Security.DepthStep(ref context);
reader.SkipVariableNumber();
int len = reader.ReadVariableNumber();
List<short> val = new List<Int16>(len);
for (int i = 0; i < len; i++)
{
val.Add(reader.ReadInt16WithOutTypeHead());
}
context.Depth--;
return val;
}
19
View Source File : Polygon.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void Unpack(BinaryReader reader)
{
NumPts = reader.ReadByte();
Stippling = (StipplingType)reader.ReadByte();
SidesType = (CullMode)reader.ReadInt32();
PosSurface = reader.ReadInt16();
NegSurface = reader.ReadInt16();
for (short i = 0; i < NumPts; i++)
VertexIds.Add(reader.ReadInt16());
if (!Stippling.HasFlag(StipplingType.NoPos))
{
for (short i = 0; i < NumPts; i++)
PosUVIndices.Add(reader.ReadByte());
}
if (SidesType == CullMode.Clockwise && !Stippling.HasFlag(StipplingType.NoNeg))
{
for (short i = 0; i < NumPts; i++)
NegUVIndices.Add(reader.ReadByte());
}
if (SidesType == CullMode.None)
{
NegSurface = PosSurface;
NegUVIndices = PosUVIndices;
}
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Network_OnMessageReceived(NetworkEvent e, bool reliable) {
var data = e.GetDataAsByteArray();
var message = Message.Deserialize(data);
var packet = Packet.Deserialize(message.bytes);
// Try to look for reserved keywords
if (packet != null && packet.Tag.StartsWith("reserved")) {
switch (packet.Tag) {
case Packet.ReservedTags.ClientJoined:
if (CurrentMode == Mode.Client) {
var cid = packet.Payload.ToShort();
Peers.Add(cid);
OnClientJoined?.Invoke(cid);
}
break;
case Packet.ReservedTags.ClientLeft:
if (CurrentMode == Mode.Client) {
var cid = packet.Payload.ToShort();
Peers.Remove(cid);
OnClientLeft?.Invoke(cid);
}
break;
case Packet.ReservedTags.ClientSetID:
if (CurrentMode == Mode.Client) {
ID = packet.Payload.ToShort();
OnReceiveID?.Invoke(ID);
}
break;
case Packet.ReservedTags.ServerClosed:
Reset();
OnRemoteServerClosed?.Invoke();
break;
}
return;
}
// If we were an intended recipient
if (message.recipients.Contains(ID)) {
if (packet != null)
OnPacketReceived?.Invoke(message.sender, packet);
else
OnBytesReceived?.Invoke(message.sender, message.bytes);
}
// If we're a server, forward the message to the intended
// recipients, except ourselves
if (CurrentMode == Mode.Server) {
foreach (var recipient in message.recipients) {
if (recipient != 0) {
if (packet == null) {
packet = new Packet();
packet.WithPayload(message.bytes);
}
var m = new Message {
sender = message.sender,
recipients = new short[] { recipient },
bytes = packet.Serialize()
};
network.SendData(
id: new ConnectionId(recipient),
data: m.Serialize(),
offset: 0,
len: m.Serialize().Length,
reliable: reliable
);
}
}
}
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Network_OnNewConnection(NetworkEvent e) {
if (CurrentMode == Mode.Server) {
var theNewID = e.ConnectionId.id;
// Notify a new client of its ID is using a reserved tag packet
var tag = Packet.ReservedTags.ClientSetID;
var packet = new Packet().With(tag, theNewID.GetBytes());
SendPacket(theNewID, packet, true);
// Using reserved tag packets, let the new client know about
// all the old clients and the old clients about the new client
foreach (var anOldID in Peers) {
tag = Packet.ReservedTags.ClientJoined;
packet = new Packet().With(tag, anOldID.GetBytes());
SendPacket(theNewID, packet, true);
tag = Packet.ReservedTags.ClientJoined;
packet = new Packet().With(tag, theNewID.GetBytes());
SendPacket(anOldID, packet, true);
}
Peers.Add(theNewID);
OnClientJoined?.Invoke(theNewID);
}
else if (CurrentMode == Mode.Idle) {
serverCID = e.ConnectionId;
CurrentMode = Mode.Client;
// Add the server as a peer. To the client, server ID is 0
Peers.Add(0);
Address = tmpAddress;
OnConnected?.Invoke();
}
}
19
View Source File : APNode.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void Network_OnNewConnection(NetworkEvent e) {
if (CurrentMode == Mode.Server) {
var theNewID = e.ConnectionId.id;
// Notify a new client of its ID is using a reserved tag packet
var tag = Packet.ReservedTags.ClientSetID;
var packet = new Packet().With(tag, theNewID.GetBytes());
SendPacket(theNewID, packet, true);
// Using reserved tag packets, let the new client know about
// all the old clients and the old clients about the new client
foreach (var anOldID in Peers) {
tag = Packet.ReservedTags.ClientJoined;
packet = new Packet().With(tag, anOldID.GetBytes());
SendPacket(theNewID, packet, true);
tag = Packet.ReservedTags.ClientJoined;
packet = new Packet().With(tag, theNewID.GetBytes());
SendPacket(anOldID, packet, true);
}
Peers.Add(theNewID);
OnClientJoined?.Invoke(theNewID);
}
else if (CurrentMode == Mode.Idle) {
serverCID = e.ConnectionId;
CurrentMode = Mode.Client;
// Add the server as a peer. To the client, server ID is 0
Peers.Add(0);
Address = tmpAddress;
OnConnected?.Invoke();
}
}
19
View Source File : GeneralObject.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public IEnumerable<short> GetCommonGroupIDs(IEnumerable<short> IDs)
{
var list = new List<short>();
var arrayIDs = IDs.ToArray();
bool found = false;
for (int i = 0; i < groupIDs.Length; i++, found = false)
for (int j = 0; j < arrayIDs.Length && !found; j++)
if (found = groupIDs[i] == arrayIDs[j])
list.Add(arrayIDs[i]);
return list;
}
19
View Source File : TokenInfoBufferCompilerTest.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
[TestMethod]
public void TestReadAndWriteFromBuffer()
{
List<short> shorts = new List<short>();
for (int i = 0; i < 10; i++) {
shorts.Add((short)i);
}
MemoryStreamWrapper buffer = new MemoryStreamWrapper(new MemoryStream(shorts.Count * 2 + 2));
buffer.WriteInt16((short)shorts.Count);
foreach (short s in shorts)
{
buffer.WriteInt16(s);
}
buffer.Stream.Position = 0;
short count = buffer.ReadInt16();
List<short> readShorts = new List<short>();
for (int i = 0; i < count; i++) {
readShorts.Add(buffer.ReadInt16());
}
for (int i = 0; i < shorts.Count; i++) {
replacedert.AreEqual(readShorts[i], shorts[i]);
}
}
19
View Source File : TokenInfoBufferCompilerTest.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
[TestMethod]
public void TestReadAndWriteFromBuffer()
{
List<short> shorts = new List<short>();
for (int i = 0; i < 10; i++) {
shorts.Add((short)i);
}
MemoryStreamWrapper buffer = new MemoryStreamWrapper(new MemoryStream(shorts.Count * 2 + 2));
buffer.WriteInt16((short)shorts.Count);
foreach (short s in shorts)
{
buffer.WriteInt16(s);
}
buffer.Stream.Position = 0;
short count = buffer.ReadInt16();
List<short> readShorts = new List<short>();
for (int i = 0; i < count; i++) {
readShorts.Add(buffer.ReadInt16());
}
for (int i = 0; i < shorts.Count; i++) {
replacedert.AreEqual(readShorts[i], shorts[i]);
}
}
19
View Source File : TokenInfoBufferCompilerTest.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
[TestMethod]
public void TestReadAndLookUpTokenInfo()
{
List<short> tokenInfo = new List<short>();
List<int> features = new List<int>();
short[] tokenInfos = new short[3];
tokenInfos[0] = 1;
tokenInfos[1] = 2;
tokenInfos[2] = 3;
int[] featureInfos = new int[2];
featureInfos[0] = 73;
featureInfos[1] = 99;
tokenInfo.Add((short)1);
tokenInfo.Add((short)2);
tokenInfo.Add((short)3);
features.Add(73);
features.Add(99);
BufferEntry entry = new BufferEntry();
entry.TokenInfo = tokenInfo;
entry.Features = features;
entry.TokenInfos = tokenInfos;
entry.FeatureInfos = featureInfos;
List<BufferEntry> bufferEntries = new List<BufferEntry>();
bufferEntries.Add(entry);
using (TokenInfoBufferCompiler compiler = new TokenInfoBufferCompiler(bufferEntries))
{
using (var outputStream = File.Create(tokenInfoFile))
{
compiler.Compile(outputStream);
}
}
using (var inputStream = File.OpenRead(tokenInfoFile))
{
using (TokenInfoBuffer tokenInfoBuffer2 = new TokenInfoBuffer(inputStream))
{
replacedert.AreEqual(99, tokenInfoBuffer2.LookupFeature(0, 1));
replacedert.AreEqual(73, tokenInfoBuffer2.LookupFeature(0, 0));
}
}
}
19
View Source File : TokenInfoBufferCompilerTest.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
[TestMethod]
public void TestCompleteLookUp()
{
Dictionary<int, string> resultMap = new Dictionary<int, string>();
resultMap[73] = "hello";
resultMap[42] = "今日は";
resultMap[99] = "素敵な世界";
List<short> tokenInfo = new List<short>();
List<int> features = new List<int>();
tokenInfo.Add((short)1);
tokenInfo.Add((short)2);
tokenInfo.Add((short)3);
features.Add(73);
features.Add(99);
BufferEntry entry = new BufferEntry();
entry.TokenInfo = tokenInfo;
entry.Features = features;
List<BufferEntry> bufferEntries = new List<BufferEntry>();
bufferEntries.Add(entry);
using (var outStream = File.Create(tokenInfoFile))
{
using (TokenInfoBufferCompiler compiler = new TokenInfoBufferCompiler(bufferEntries))
{
compiler.Compile(outStream);
}
}
using (var inStream = File.OpenRead(tokenInfoFile))
{
using (TokenInfoBuffer tokenInfoBuffer = new TokenInfoBuffer(inStream))
{
BufferEntry result = tokenInfoBuffer.LookupEntry(0);
replacedert.AreEqual("hello", resultMap[result.FeatureInfos[0]]);
replacedert.AreEqual("素敵な世界", resultMap[result.FeatureInfos[1]]);
}
}
}
19
View Source File : CardCollection.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
public void Add(short cardId)
{
CardIds.Add(cardId);
}
19
View Source File : Battle_Pack_Save.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
public override void Load(BinaryReader reader)
{
Unk1 = reader.ReadByte();
State = (BattlePackSaveState) reader.ReadInt32();
NumDuelsCompleted = reader.ReadInt32();
NumDuelsWon = reader.ReadInt32();
NumDuelsLost = reader.ReadInt32();
Unk2 = reader.ReadInt32();
DuelResult1 = (BattlePackDuelResult) reader.ReadInt32();
DuelResult2 = (BattlePackDuelResult) reader.ReadInt32();
DuelResult3 = (BattlePackDuelResult) reader.ReadInt32();
DuelResult4 = (BattlePackDuelResult) reader.ReadInt32();
DuelResult5 = (BattlePackDuelResult) reader.ReadInt32();
LoadDeckData(reader);
Type = (BattlePackType) reader.ReadInt32();
for (var i = 0; i < NumDraftedCards; i++)
{
var cardId = reader.ReadInt16();
if (cardId > 0) DraftedCards.Add(cardId);
}
Unk3 = reader.ReadInt32();
Unk4 = reader.ReadInt32();
Unk5 = reader.ReadInt32();
Unk6 = reader.ReadByte();
LoadSealedCards(reader, SealedCards1);
LoadSealedCards(reader, SealedCards2);
LoadSealedCards(reader, SealedCards3);
}
19
View Source File : Battle_Pack_Save.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
private static void LoadSealedCards(BinaryReader reader, List<short> sealedCards)
{
var numSealedCards = reader.ReadInt32();
for (var i = 0; i < NumSealedCardsPerSegment; i++)
{
var cardId = reader.ReadInt16();
if (cardId > 0) sealedCards.Add(cardId);
}
}
19
View Source File : Deck_Save_Database.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
public void LoadDeckData(BinaryReader Reader)
{
DeckName = Encoding.Unicode.GetString(Reader.ReadBytes(Constants.DeckNameByteLen)).TrimEnd('\0');
var NumMainDeckCards = Reader.ReadInt16();
var NumSideDeckCards = Reader.ReadInt16();
var NumExtraDeckCards = Reader.ReadInt16();
for (var Count = 0; Count < MaxMainDeckCards; Count++)
{
var CardId = Reader.ReadInt16();
if (CardId > 0) MainDeckCards.Add(CardId);
}
for (var Count = 0; Count < MaxSideDeckCards; Count++)
{
var CardId = Reader.ReadInt16();
if (CardId > 0) SideDeckCards.Add(CardId);
}
for (var Count = 0; Count < MaxExtraDeckCards; Count++)
{
var CardId = Reader.ReadInt16();
if (CardId > 0) ExtraDeckCards.Add(CardId);
}
Reader.ReadBytes(12);
Reader.ReadBytes(12);
Reader.ReadUInt32();
Reader.ReadUInt32();
Reader.ReadUInt32();
DeckAvatarId = Reader.ReadInt32();
Reader.ReadUInt32();
Reader.ReadUInt32();
IsDeckComplete = Reader.ReadUInt32() == 1;
}
19
View Source File : LeveledCreatureRecord.cs
License : GNU General Public License v3.0
Project Creator : arycama
License : GNU General Public License v3.0
Project Creator : arycama
public override void Initialize(System.IO.BinaryReader reader, RecordHeader header)
{
while (reader.BaseStream.Position < header.DataEndPos)
{
var type = (SubRecordType)reader.ReadInt32();
var size = reader.ReadInt32();
switch (type)
{
case SubRecordType.Id:
name = reader.ReadString(size);
break;
case SubRecordType.Data:
calculateFromAllLevelsLessThanPCsLevel = reader.ReadInt32();
break;
case SubRecordType.NextName:
chanceNone = reader.ReadByte();
break;
case SubRecordType.Index:
index = reader.ReadInt32();
break;
case SubRecordType.CreatureName:
creatureNames.Add(reader.ReadString(size));
break;
case SubRecordType.IntValue:
pcLevel.Add(reader.ReadInt16());
break;
}
}
}
19
View Source File : AnimationTrack.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public override void Optimise()
{
// Eliminate duplicate keyframes from 2nd to penultimate keyframe
// NB only eliminate middle keys from sequences of 5+ identical keyframes
// since we need to preserve the boundary keys in place, and we need
// 2 at each end to preserve tangents for spline interpolation
var lasttrans = Vector3.Zero;
var lastscale = Vector3.Zero;
var lastorientation = Quaternion.Zero;
var tolerance = 1e-3f;
var quatTolerance = 1e-3f;
ushort k = 0;
ushort dupKfCount = 0;
var removeList = new List<short>();
for (var i = 0; i < keyFrameList.Count; i++)
{
var keyFrame = keyFrameList[i];
var kf = (TransformKeyFrame)keyFrame;
var newtrans = kf.Translate;
var newscale = kf.Scale;
var neworientation = kf.Rotation;
// Ignore first keyframe; now include the last keyframe as we eliminate
// only k-2 in a group of 5 to ensure we only eliminate middle keys
if (i != 0 && newtrans.DifferenceLessThan(lasttrans, tolerance) &&
newscale.DifferenceLessThan(lastscale, tolerance) && neworientation.Equals(lastorientation, quatTolerance))
{
++dupKfCount;
// 4 indicates this is the 5th duplicate keyframe
if (dupKfCount == 4)
{
// remove the 'middle' keyframe
removeList.Add((short)(k - 2));
--dupKfCount;
}
}
else
{
// reset
dupKfCount = 0;
lasttrans = newtrans;
lastscale = newscale;
lastorientation = neworientation;
}
}
// Now remove keyframes, in reverse order to avoid index revocation
for (var i = removeList.Count - 1; i >= 0; i--)
{
RemoveKeyFrame(removeList[i]);
}
}
19
View Source File : CharacterScreenLoadHandler.cs
License : GNU General Public License v3.0
Project Creator : BlowaXD
License : GNU General Public License v3.0
Project Creator : BlowaXD
protected override async Task Handle(EntryPointPacketBase packet, ISession session)
{
if (session.Account == null && !await AccountChecks(packet, session))
{
return;
}
Log.Info($"[LOAD_CHARACTERS] {session.Account.Name}");
IEnumerable<CharacterDto> characters = await _characterService.GetActiveByAccountIdAsync(session.Account.Id);
// load characterlist packetBase for each characterEnreplacedy in Player
await session.SendPacketAsync(new CListStartPacket { Type = 0 });
foreach (CharacterDto character in characters)
{
ItemInstanceDto[] equipment = new ItemInstanceDto[16];
IEnumerable<ItemInstanceDto> inventory = await _itemInstanceService.GetWearByCharacterIdAsync(character.Id);
foreach (ItemInstanceDto equipmentEntry in inventory)
{
equipment[(short)equipmentEntry.Item.EquipmentSlot] = equipmentEntry;
}
List<short?> petlist = new List<short?>();
CharacterMateDto[] mates = await _characterMateService.GetMatesByCharacterIdAsync(character.Id);
for (int i = 0; i < 26; i++)
{
if (mates.Length > i)
{
petlist.Add(mates[i]?.Skin ?? -1);
petlist.Add(mates[i]?.NpcMonsterId ?? -1);
}
else
{
petlist.Add(-1);
}
}
await session.SendPacketAsync(new ClistPacketBase
{
Slot = character.Slot,
Name = character.Name,
Unknown = 0,
Gender = character.Gender,
HairStyle = character.HairStyle,
HairColor = character.HairColor,
Unknown1 = 0,
Clreplaced = character.Clreplaced,
Level = character.Level,
HeroLevel = character.HeroLevel,
Equipments = new List<short?>
{
(short?)(equipment[(byte)EquipmentType.Hat]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.Armor]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.WeaponSkin]?.ItemId ?? (equipment[(byte)EquipmentType.MainWeapon]?.ItemId ?? -1)),
(short?)(equipment[(byte)EquipmentType.SecondaryWeapon]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.Mask]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.Fairy]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.CostumeSuit]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.CostumeHat]?.ItemId ?? -1)
},
JobLevel = character.JobLevel,
QuestCompletion = 1,
QuestPart = 1,
Pets = petlist,
Design = equipment[(byte)EquipmentType.Hat]?.Item.IsColored == true ? equipment[(byte)EquipmentType.Hat].Design : 0,
Unknown3 = 0
});
}
await session.SendPacketAsync(new ClistEndPacketBase());
}
19
View Source File : CharacterScreenLoadHandler.cs
License : GNU General Public License v3.0
Project Creator : BlowaXD
License : GNU General Public License v3.0
Project Creator : BlowaXD
protected override async Task Handle(EntryPointPacketBase packet, ISession session)
{
if (session.Account == null && !await AccountChecks(packet, session))
{
return;
}
Log.Info($"[LOAD_CHARACTERS] {session.Account.Name}");
IEnumerable<CharacterDto> characters = await _characterService.GetActiveByAccountIdAsync(session.Account.Id);
// load characterlist packetBase for each characterEnreplacedy in Player
await session.SendPacketAsync(new CListStartPacket { Type = 0 });
foreach (CharacterDto character in characters)
{
ItemInstanceDto[] equipment = new ItemInstanceDto[16];
IEnumerable<ItemInstanceDto> inventory = await _itemInstanceService.GetWearByCharacterIdAsync(character.Id);
foreach (ItemInstanceDto equipmentEntry in inventory)
{
equipment[(short)equipmentEntry.Item.EquipmentSlot] = equipmentEntry;
}
List<short?> petlist = new List<short?>();
CharacterMateDto[] mates = await _characterMateService.GetMatesByCharacterIdAsync(character.Id);
for (int i = 0; i < 26; i++)
{
if (mates.Length > i)
{
petlist.Add(mates[i]?.Skin ?? -1);
petlist.Add(mates[i]?.NpcMonsterId ?? -1);
}
else
{
petlist.Add(-1);
}
}
await session.SendPacketAsync(new ClistPacketBase
{
Slot = character.Slot,
Name = character.Name,
Unknown = 0,
Gender = character.Gender,
HairStyle = character.HairStyle,
HairColor = character.HairColor,
Unknown1 = 0,
Clreplaced = character.Clreplaced,
Level = character.Level,
HeroLevel = character.HeroLevel,
Equipments = new List<short?>
{
(short?)(equipment[(byte)EquipmentType.Hat]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.Armor]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.WeaponSkin]?.ItemId ?? (equipment[(byte)EquipmentType.MainWeapon]?.ItemId ?? -1)),
(short?)(equipment[(byte)EquipmentType.SecondaryWeapon]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.Mask]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.Fairy]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.CostumeSuit]?.ItemId ?? -1),
(short?)(equipment[(byte)EquipmentType.CostumeHat]?.ItemId ?? -1)
},
JobLevel = character.JobLevel,
QuestCompletion = 1,
QuestPart = 1,
Pets = petlist,
Design = equipment[(byte)EquipmentType.Hat]?.Item.IsColored == true ? equipment[(byte)EquipmentType.Hat].Design : 0,
Unknown3 = 0
});
}
await session.SendPacketAsync(new ClistEndPacketBase());
}
19
View Source File : XaAdpcm.cs
License : MIT License
Project Creator : BluestormDNA
License : MIT License
Project Creator : BluestormDNA
private static List<short> resampleTo44100Hz(List<short> samples, bool isStereo, bool is18900hz, int channel) {
List<short> resamples = isStereo ? stereoResamples : monoResamples;
resamples.Clear();
//todo handle 18900hz
for (int i = 0; i < samples.Count; i++) {
resampleRingBuffer[channel][resamplePointer++ & 0x1F] = samples[i];
sixStep--;
if (sixStep == 0) {
sixStep = 6;
for (int table = 0; table < 7; table++) {
resamples.Add(zigZagInterpolate(resamplePointer, table, channel));
}
}
}
//Console.WriteLine("resamples Length" + resamples.Count); //2352 stereo ? 4704 mono
return resamples;
}
19
View Source File : GridRenderer.cs
License : MIT License
Project Creator : ccajas
License : MIT License
Project Creator : ccajas
public void SetGridSize(int gridSize)
{
// Add a 2D grid in the X, Z plane
int j = 0;
// Set vertices for lines on X axis, then Z axis
for (int i = -gridSize; i <= gridSize; i++)
{
Color color = (i == 0) ? Color.LightGray : Color.Gray;
gridVertices.Add(new VertexPositionColor(new Vector3(i, 0, -gridSize), color));
gridVertices.Add(new VertexPositionColor(new Vector3(i, 0, gridSize), color));
gridIndices.Add((short)j);
gridIndices.Add((short)(j + 1));
j = j + 2;
}
for (int i = -gridSize; i <= gridSize; i++)
{
Color color = (i == 0) ? Color.LightGray : Color.Gray;
gridVertices.Add(new VertexPositionColor(new Vector3(-gridSize, 0, i), color));
gridVertices.Add(new VertexPositionColor(new Vector3(gridSize, 0, i), color));
gridIndices.Add((short)j);
gridIndices.Add((short)(j + 1));
j = j + 2;
}
}
19
View Source File : FixedMemoryBlock.cs
License : Apache License 2.0
Project Creator : cdy816
License : Apache License 2.0
Project Creator : cdy816
public List<short> ReadShorts(long offset, int count)
{
List<short> re = new List<short>(count);
for (int i = 0; i < count; i++)
{
re.Add(ReadShort((int)offset + 2 * i));
}
return re;
}
19
View Source File : FixedMemoryBlock.cs
License : Apache License 2.0
Project Creator : cdy816
License : Apache License 2.0
Project Creator : cdy816
public static List<short> ToShortList(this FixedMemoryBlock memory)
{
List<short> re = new List<short>((int)(memory.Length / 2));
memory.Position = 0;
while (memory.Position < memory.Length)
{
re.Add(memory.ReadShort());
}
return re;
}
19
View Source File : MemorySpan.cs
License : Apache License 2.0
Project Creator : cdy816
License : Apache License 2.0
Project Creator : cdy816
public static List<short> ToShortList(this MemorySpan memory)
{
List<short> re = new List<short>((int)(memory.Length / 2));
memory.Position = 0;
while (memory.Position < memory.Length)
{
re.Add(memory.ReadShort());
}
return re;
}
19
View Source File : HisDataBuffer.cs
License : Apache License 2.0
Project Creator : cdy816
License : Apache License 2.0
Project Creator : cdy816
public List<short> ReadShorts(long offset, int count)
{
List<short> re = new List<short>(count);
for (int i = 0; i < count; i++)
{
re.Add(ReadShort(offset + 2 * i));
}
return re;
}
19
View Source File : LewiWu.cs
License : MIT License
Project Creator : dbogatov
License : MIT License
Project Creator : dbogatov
public Ciphertext.Right EncryptRight(byte[] leftKey, byte[] rightKey, uint input)
{
OnOperation(SchemeOperation.Encrypt);
List<List<short>> result = new List<List<short>>();
byte[] nonce = new byte[ALPHA / 8];
G.NextBytes(nonce);
for (int i = 0; i < n; i++)
{
int shift = (_bitsInBlock * (n - i));
uint yi = (input << (_bitsInBlock * i)) >> (_bitsInBlock * (n - 1));
uint ytoi = shift > 31 ? 0 : input >> shift;
List<short> v = new List<short>();
for (uint j = 0; j < d; j++)
{
uint js = P.InversePRP(
(byte)j,
F.PRF(
rightKey,
BitConverter.GetBytes(ytoi)
),
(byte)_bitsInBlock
);
byte[] ytoij = Concatenate(ytoi, j);
var cmp = CMP(js, yi);
var hash = Hash(nonce, F.PRF(leftKey, ytoij));
short vi = (short)(cmp + hash);
v.Add(vi);
}
result.Add(v);
}
return new Ciphertext.Right
{
shorts = result,
nonce = nonce
};
}
19
View Source File : WaveStreamReader.cs
License : MIT License
Project Creator : dereksorensen
License : MIT License
Project Creator : dereksorensen
private void DecodeTo16Bit(byte[] buffer, out short[] samples)
{
List<short> result = new List<short>();
using (BufferStream raw = new BufferStream(buffer))
using (BufferStream decoded = new BufferStream())
{
// Convert 32bit WAV
if (Bits == 32)
{
if (_type == AudioFormat.PCM)
{
while (raw.HasRemaining)
{
int sample = raw.GetInt32();
short temp = (short)(sample >> 16);
result.Add(temp);
}
}
// Convert 32bit Float WAV
else if (_type == AudioFormat.Float)
{
while (raw.HasRemaining)
{
float sample = raw.GetFloat();
short temp = (short)(sample * 32767.0f);
result.Add(temp);
}
}
}
samples = result.ToArray();
}
}
19
View Source File : RankingEvaluator.cs
License : MIT License
Project Creator : dotnet
License : MIT License
Project Creator : dotnet
public void Update(short label, Single output)
{
_queryLabels.Add(label);
_queryOutputs.Add(output);
}
19
View Source File : RankingEvaluator.cs
License : MIT License
Project Creator : dotnet
License : MIT License
Project Creator : dotnet
protected override void ProcessExample(RowCursorState state, short label, Single score)
{
state.QueryLabels.Add(label);
state.QueryOutputs.Add(score);
}
19
View Source File : Codecs.cs
License : MIT License
Project Creator : dotnet
License : MIT License
Project Creator : dotnet
public override void Write(in DateTimeOffset value)
{
Contracts.replacedert(_offsets != null, "writer was already committed");
_ticks.Add(value.DateTime.Ticks);
//DateTimeOffset exposes its offset as a TimeSpan, but internally it uses short and in minutes.
//https://github.com/dotnet/coreclr/blob/9499b08eefd895158c3f3c7834e185a73619128d/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs#L51-L53
//https://github.com/dotnet/coreclr/blob/9499b08eefd895158c3f3c7834e185a73619128d/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs#L286-L292
//From everything online(ISO8601, RFC3339, SQL Server doc, the offset supports the range -14 to 14 hours, and only supports minute precision.
_offsets.Add((short)(value.Offset.TotalMinutes));
}
19
View Source File : FastTree.cs
License : MIT License
Project Creator : dotnet
License : MIT License
Project Creator : dotnet
private void MakeBoundariesAndCheckLabels(out long missingInstances, out long totalInstances)
{
using (var ch = Host.Start("InitBoundariesAndLabels"))
using (var pch = Host.StartProgressChannel("FastTree data preparation"))
{
long featureValues = 0;
// Warn at about 2 GB usage.
const long featureValuesWarnThreshold = (2L << 30) / sizeof(double);
bool featureValuesWarned = false;
const string featureValuesWarning = "We seem to be processing a lot of data. Consider using the FastTree diskTranspose+ (or dt+) option, for slower but more memory efficient transposition.";
const int queryChunkSize = 100;
// Populate the feature values array and labels.
ch.Info("Changing data from row-wise to column-wise");
long pos = 0;
double rowCountDbl = (double?)_data.Data.GetRowCount() ?? double.NaN;
pch.SetHeader(new ProgressHeader("examples"),
e => e.SetProgress(0, pos, rowCountDbl));
// REVIEW: Should we ignore rows with bad label, weight, or group? The previous code seemed to let
// them through (but filtered out bad features).
CursOpt curOptions = CursOpt.Label | CursOpt.Features;
bool hasGroup = false;
if (PredictionKind == PredictionKind.Ranking)
{
hasGroup = _data.Schema.Group != null;
if (hasGroup)
curOptions |= CursOpt.Group;
}
else
{
if (_data.Schema.Group != null)
ch.Warning("This is not ranking problem, Group Id '{0}' column will be ignored", _data.Schema.Group.Value.Name);
}
if (_data.Schema.Weight.HasValue)
curOptions |= CursOpt.Weight;
using (var cursor = new FloatLabelCursor(_data, curOptions))
{
ulong groupPrev = 0;
while (cursor.MoveNext())
{
pos = cursor.KeptRowCount - 1;
int index = checked((int)pos);
ch.replacedert(pos >= 0);
// If we have no group, then the group number should not change.
Host.replacedert(hasGroup || cursor.Group == groupPrev);
if (hasGroup)
{
// If we are either at the start of iteration, or a new
// group has started, add the boundary and register the
// new group identifier.
if (pos == 0 || cursor.Group != groupPrev)
{
_boundaries.Add(index);
groupPrev = cursor.Group;
}
}
else if (pos % queryChunkSize == 0)
{
// If there are no groups, it is best to just put the
// boundaries at regular intervals.
_boundaries.Add(index);
}
if (UsingMaxLabel)
{
if (cursor.Label < 0 || cursor.Label > MaxLabel)
throw ch.Except("Found invalid label {0}. Value should be between 0 and {1}, inclusive.", cursor.Label, MaxLabel);
}
foreach (var kvp in cursor.Features.Items())
_instanceList[kvp.Key].Add(index, kvp.Value);
_actualTargets.Add(cursor.Label);
if (_weights != null)
_weights.Add(cursor.Weight);
_targetsList.Add((short)cursor.Label);
featureValues += cursor.Features.GetValues().Length;
if (featureValues > featureValuesWarnThreshold && !featureValuesWarned)
{
ch.Warning(featureValuesWarning);
featureValuesWarned = true;
}
}
_boundaries.Add(checked((int)cursor.KeptRowCount));
totalInstances = cursor.KeptRowCount;
missingInstances = cursor.BadFeaturesRowCount;
}
ch.Check(totalInstances > 0, "All instances skipped due to missing features.");
if (missingInstances > 0)
ch.Warning("Skipped {0} instances with missing features during training", missingInstances);
}
}
19
View Source File : SubstitutionArrayEntry.cs
License : MIT License
Project Creator : EricZimmerman
License : MIT License
Project Creator : EricZimmerman
public string GetDatareplacedtring()
{
int index;
switch (ValType)
{
case TagBuilder.ValueType.NullType:
return string.Empty;
case TagBuilder.ValueType.StringType:
var s = Encoding.Unicode.GetString(DataBytes).Trim('\0');
s = Regex.Replace(s, @"\p{C}+", ", ");
return s;
case TagBuilder.ValueType.AnsiStringType:
var sa = Encoding.GetEncoding(1252).GetString(DataBytes).Trim('\0');
sa = Regex.Replace(sa, @"\p{C}+", ", ");
return sa;
case TagBuilder.ValueType.Int8Type:
return ((sbyte) DataBytes[0]).ToString();
case TagBuilder.ValueType.UInt8Type:
return DataBytes[0].ToString();
case TagBuilder.ValueType.Int16Type:
return BitConverter.ToInt16(DataBytes, 0).ToString();
case TagBuilder.ValueType.UInt16Type:
return BitConverter.ToUInt16(DataBytes, 0).ToString();
case TagBuilder.ValueType.Int32Type:
return BitConverter.ToInt32(DataBytes, 0).ToString();
case TagBuilder.ValueType.UInt32Type:
return BitConverter.ToUInt32(DataBytes, 0).ToString();
case TagBuilder.ValueType.Int64Type:
return BitConverter.ToInt64(DataBytes, 0).ToString();
case TagBuilder.ValueType.UInt64Type:
return BitConverter.ToUInt64(DataBytes, 0).ToString();
case TagBuilder.ValueType.Real32Type:
return BitConverter.ToSingle(DataBytes, 0).ToString(CultureInfo.InvariantCulture);
case TagBuilder.ValueType.Real64Type:
return BitConverter.ToDouble(DataBytes, 0).ToString(CultureInfo.InvariantCulture);
case TagBuilder.ValueType.BoolType:
return BitConverter.ToBoolean(DataBytes, 0).ToString();
case TagBuilder.ValueType.BinaryType:
return BitConverter.ToString(DataBytes);
case TagBuilder.ValueType.GuidType:
var g = new Guid(DataBytes);
return g.ToString();
case TagBuilder.ValueType.SizeTType:
return BitConverter.ToString(DataBytes);
case TagBuilder.ValueType.FileTimeType:
var fts = DateTimeOffset.FromFileTime(BitConverter.ToInt64(DataBytes, 0)).ToUniversalTime();
return fts.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
case TagBuilder.ValueType.SysTimeType:
var sts = GetSystemTime(DataBytes);
return sts.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
case TagBuilder.ValueType.SidType:
return ConvertHexStringToSidString(DataBytes);
case TagBuilder.ValueType.HexInt32Type:
return $"0x{BitConverter.ToInt32(DataBytes, 0):X}";
case TagBuilder.ValueType.HexInt64Type:
return $"0x{BitConverter.ToInt64(DataBytes, 0):X}";
case TagBuilder.ValueType.EvtXml:
case TagBuilder.ValueType.EvtHandle:
return "UNKNOWN: Please submit to [email protected]!";
case TagBuilder.ValueType.BinXmlType:
return "BinaryXML";
case TagBuilder.ValueType.ArrayUnicodeString:
var tsu = Encoding.Unicode.GetString(DataBytes)
.Split(new[] {'\0'}, StringSplitOptions.RemoveEmptyEntries);
return string.Join(", ", tsu).Trim('\0');
case TagBuilder.ValueType.ArrayAsciiString:
var tsa = Encoding.GetEncoding(1252).GetString(DataBytes)
.Split(new[] {'\0'}, StringSplitOptions.RemoveEmptyEntries);
return string.Join(", ", tsa).Trim('\0');
case TagBuilder.ValueType.Array64BitIntSigned:
var a64i = new List<long>();
index = 0;
while (index < DataBytes.Length)
{
var ul = BitConverter.ToInt64(DataBytes, index);
index += 8;
a64i.Add(ul);
}
return string.Join(",", a64i);
case TagBuilder.ValueType.Array64BitIntUnsigned:
var a64ui = new List<ulong>();
index = 0;
while (index < DataBytes.Length)
{
var ul = BitConverter.ToUInt64(DataBytes, index);
index += 8;
a64ui.Add(ul);
}
return string.Join(",", a64ui);
case TagBuilder.ValueType.Array16BitIntUnsigned:
var a16ui = new List<ushort>();
index = 0;
while (index < DataBytes.Length)
{
var ul = BitConverter.ToUInt16(DataBytes, index);
index += 2;
a16ui.Add(ul);
}
return string.Join(",", a16ui);
case TagBuilder.ValueType.Array16BitIntSigned:
var a16i = new List<short>();
index = 0;
while (index < DataBytes.Length)
{
var ul = BitConverter.ToInt16(DataBytes, index);
index += 2;
a16i.Add(ul);
}
return string.Join(",", a16i);
case TagBuilder.ValueType.Array32BitIntSigned:
var a32i = new List<int>();
index = 0;
while (index < DataBytes.Length)
{
var ul = BitConverter.ToInt32(DataBytes, index);
index += 4;
a32i.Add(ul);
}
return string.Join(",", a32i);
case TagBuilder.ValueType.Array32BitIntUnsigned:
var a32ui = new List<uint>();
index = 0;
while (index < DataBytes.Length)
{
var ul = BitConverter.ToUInt32(DataBytes, index);
index += 4;
a32ui.Add(ul);
}
return string.Join(",", a32ui);
case TagBuilder.ValueType.Array8BitIntSigned:
var sb = new List<sbyte>();
index = 0;
while (index < DataBytes.Length)
{
sb.Add((sbyte) DataBytes[index]);
index += 1;
}
return string.Join(",", sb);
case TagBuilder.ValueType.Array8BitIntUnsigned:
var b = new List<byte>();
index = 0;
while (index < DataBytes.Length)
{
b.Add(DataBytes[index]);
index += 1;
}
return string.Join(",", b);
case TagBuilder.ValueType.ArrayFloat32Bit:
var sl = new List<float>();
index = 0;
while (index < DataBytes.Length)
{
var sn = BitConverter.ToSingle(DataBytes, index);
index += 4;
sl.Add(sn);
}
return string.Join(",", sl);
case TagBuilder.ValueType.ArrayFloat64Bit:
var dl = new List<double>();
index = 0;
while (index < DataBytes.Length)
{
var dn = BitConverter.ToDouble(DataBytes, index);
index += 4;
dl.Add(dn);
}
return string.Join(",", dl);
case TagBuilder.ValueType.ArrayBool:
var boo = new List<bool>();
index = 0;
while (index < DataBytes.Length)
{
var bv = BitConverter.ToInt32(DataBytes, index) != 0;
boo.Add(bv);
index += 4;
}
return string.Join(",", boo);
case TagBuilder.ValueType.ArrayFileTime:
var dto = new List<string>();
index = 0;
while (index < DataBytes.Length)
{
var ts = DateTime.FromFileTime(BitConverter.ToInt64(DataBytes, index)).ToUniversalTime();
dto.Add(ts.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
index += 8;
}
return string.Join(",", dto);
case TagBuilder.ValueType.ArraySystemTime:
var st = new List<string>();
index = 0;
while (index < DataBytes.Length)
{
var stb = new byte[16];
Buffer.BlockCopy(DataBytes, index, stb, 0, 16);
index += 16;
var nst = GetSystemTime(stb).ToUniversalTime();
st.Add(nst.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
}
return string.Join(",", st);
case TagBuilder.ValueType.ArrayGuid:
var gl = new List<string>();
index = 0;
while (index < DataBytes.Length)
{
var gb = new byte[16];
Buffer.BlockCopy(DataBytes, index, gb, 0, 16);
index += 16;
var ng = new Guid(gb);
gl.Add(ng.ToString());
}
return string.Join(",", gl);
case TagBuilder.ValueType.ArraySizeType:
case TagBuilder.ValueType.ArraySids:
case TagBuilder.ValueType.Array32BitHex:
case TagBuilder.ValueType.Array64BitHex:
default:
throw new ArgumentOutOfRangeException(
$"When converting subsreplacedution array entry to string, ran into unknown Value type: {ValType}. Please submit to [email protected]!");
}
}
19
View Source File : G4tx.cs
License : GNU General Public License v3.0
Project Creator : FanTranslatorsInternational
License : GNU General Public License v3.0
Project Creator : FanTranslatorsInternational
public void Save(Stream output, IList<IArchiveFileInfo> files)
{
var crc = Crc32.Default;
var g4txFiles = files.Cast<G4txArchiveFileInfo>().ToArray();
using var bw = new BinaryWriterX(output);
using var br = new BinaryReaderX(output);
// Calculate offsets
var subEntryCount = g4txFiles.Sum(x => x.Entries.Count);
var entryOffset = HeaderSize;
var subEntryOffset = entryOffset + files.Count * EntrySize;
var hashOffset = (subEntryOffset + subEntryCount * SubEntrySize + 0xF) & ~0xF;
var idOffset = hashOffset + (files.Count + subEntryCount) * 4;
var stringOffset = (idOffset + (files.Count + subEntryCount) + 0x3) & ~0x3;
var stringContentOffset = (stringOffset + (files.Count + subEntryCount) * 2 + 0x7) & ~0x7;
var dataOffset = (stringContentOffset + g4txFiles
.Sum(x => x.FilePath.GetNameWithoutExtension().Length + 1 + x.Entries.Sum(y => y.Name.Length + 1)) + 0xF) & ~0xF;
// Write files
var dataPosition = dataOffset;
foreach (var file in g4txFiles)
{
output.Position = dataPosition;
var writtenSize = file.SaveFileData(output);
// Update file entry
output.Position = dataPosition;
var nxtchHeader = br.ReadType<NxtchHeader>();
file.Entry.nxtchOffset = dataPosition - dataOffset;
file.Entry.nxtchSize = (int)(output.Length - dataPosition);
file.Entry.width = (short)nxtchHeader.width;
file.Entry.height = (short)nxtchHeader.height;
dataPosition = (int)((dataPosition + writtenSize + 0xF) & ~0xF);
}
// Write strings
var stringContentPosition = stringContentOffset;
var names = files.Select(x => x.FilePath.GetNameWithoutExtension())
.Concat(g4txFiles.SelectMany(x => x.Entries.Select(y => y.Name))).ToArray();
var stringOffsets = new List<short>();
foreach (var name in names)
{
stringOffsets.Add((short)(stringContentPosition - stringOffset));
output.Position = stringContentPosition;
bw.WriteString(name, Encoding.ASCII, false);
stringContentPosition += name.Length + 1;
}
// Write string offsets
output.Position = stringOffset;
bw.WriteMultiple(stringOffsets);
// Write ids
var ids = g4txFiles.Select(x => x.Id).Concat(g4txFiles.SelectMany(x => x.Entries.Select(y => y.Id)));
output.Position = idOffset;
bw.WriteMultiple(ids);
// Write hashes
var hashes = names.Select(x => crc.ComputeValue(x));
output.Position = hashOffset;
bw.WriteMultiple(hashes);
// Write sub entries
var subEntries = g4txFiles.SelectMany(x => x.Entries.Select(y => y.EntryEntry)).ToArray();
output.Position = subEntryOffset;
bw.WriteMultiple(subEntries);
// Write entries
var entries = g4txFiles.Select(x => x.Entry);
output.Position = entryOffset;
bw.WriteMultiple(entries);
// Write header
_header.textureCount = (short)files.Count;
_header.tableSize = stringContentPosition - HeaderSize;
_header.textureDataSize = (int)output.Length - dataOffset;
_header.subTextureCount = (byte)subEntries.Length;
_header.totalCount = (short)(_header.textureCount + _header.subTextureCount);
output.Position = 0;
bw.WriteType(_header);
}
19
View Source File : BinaryReaderExtension.List.cs
License : MIT License
Project Creator : FingerCaster
License : MIT License
Project Creator : FingerCaster
public static List<short> ReadInt16List(this BinaryReader binaryReader)
{
int count = binaryReader.Read7BitEncodedInt32();
List<short> list = new List<short>(count);
for (int i = 0; i < count; i++)
{
list.Add(binaryReader.ReadInt16());
}
return list;
}
19
View Source File : DataTableExtension.List.cs
License : MIT License
Project Creator : FingerCaster
License : MIT License
Project Creator : FingerCaster
public static List<short> ParseInt16List(string value)
{
if (string.IsNullOrEmpty(value) || value.ToLowerInvariant().Equals("null"))
return null;
string[] splitValue = value.Split(',');
List<short> list = new List<short>(splitValue.Length);
for (int i = 0; i < splitValue.Length; i++)
{
list.Add(Int16.Parse(splitValue[i]));
}
return list;
}
19
View Source File : LogicalColumnReader.cs
License : Apache License 2.0
Project Creator : G-Research
License : Apache License 2.0
Project Creator : G-Research
private static Array ReadArrayLeafLevel(Node node, BufferedReader<TPhysical> valueReader, LogicalRead<TLogical, TPhysical>.Converter converter, short repereplacedionLevel, short definitionLevel)
{
var defnLevel = new List<short>();
var values = new List<TPhysical>();
var firstValue = true;
var innerNodeIsOptional = node.Repereplacedion == Repereplacedion.Optional;
definitionLevel += (short) (innerNodeIsOptional ? 1 : 0);
while (!valueReader.IsEofDefinition)
{
var defn = valueReader.GetCurrentDefinition();
if (!firstValue && defn.RepLevel < repereplacedionLevel)
{
break;
}
if (defn.DefLevel == definitionLevel)
{
values.Add(valueReader.ReadValue());
}
else if (innerNodeIsOptional && (defn.DefLevel != definitionLevel))
{
// Value is null, skip
}
else
{
throw new Exception("Definition levels read from file do not match up with schema.");
}
defnLevel.Add(defn.DefLevel);
valueReader.NextDefinition();
firstValue = false;
}
var dest = new TLogical[defnLevel.Count];
converter(values.ToArray(), defnLevel.ToArray(), dest, definitionLevel);
return dest;
}
19
View Source File : ClientService.cs
License : GNU Lesser General Public License v3.0
Project Creator : GavinYellow
License : GNU Lesser General Public License v3.0
Project Creator : GavinYellow
public void ActiveItem(bool active, params ITag[] items)
{
Dictionary<IGroup, List<short>> dict = new Dictionary<IGroup, List<short>>();
for (int i = 0; i < items.Length; i++)
{
List<short> list = null;
ITag item = items[i];
dict.TryGetValue(item.Parent, out list);
if (list != null)
{
list.Add(item.ID);
}
else
dict.Add(item.Parent, new List<short> { item.ID });
}
foreach (var grp in dict)
{
grp.Key.SetActiveState(active, grp.Value.ToArray());
}
}
19
View Source File : CityShopEditor.cs
License : MIT License
Project Creator : Greavesy1899
License : MIT License
Project Creator : Greavesy1899
private void SaveFromDataGrid()
{
List<string> enreplacedies = new List<string>();
List<List<short>> translocators = new List<List<short>>();
translocators = new List<List<short>>();
for (int i = 1; i != dataGridView1.Rows[0].Cells.Count; i++)
translocators.Add(new List<short>());
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].GetType() == typeof(DataGridViewTextBoxCell))
{
if(row.Cells[0].Value != null)
enreplacedies.Add((row.Cells[0] as DataGridViewTextBoxCell).Value.ToString());
}
for (int i = 1; i != dataGridView1.Rows[0].Cells.Count; i++)
{
if (row.Cells[0].Value != null)
translocators[i - 1].Add(short.Parse(row.Cells[i].Value.ToString()));
}
}
currentData.Entries = enreplacedies.ToArray();
for(int i = 0; i != currentData.Translokators.Count; i++)
{
CityShops.AreaData.TranslokatorData data = currentData.Translokators[i];
data.EnreplacedyProperties = translocators[i];
}
}
19
View Source File : CityShops.cs
License : MIT License
Project Creator : Greavesy1899
License : MIT License
Project Creator : Greavesy1899
public void ReadFromFile(BinaryReader reader, int numEnreplacedies, int fileVersion)
{
nameKey = reader.ReadUInt16();
positionX = reader.ReadSingle();
positionY = reader.ReadSingle();
mapMarkerIconID = reader.ReadInt32();
mapMarkerStringID = reader.ReadInt32();
if(fileVersion == 9)
reader.ReadByte();
enreplacedyProperties = new List<short>();
for (int i = 0; i != numEnreplacedies; i++)
enreplacedyProperties.Add(reader.ReadInt16());
}
19
View Source File : CityShops.cs
License : MIT License
Project Creator : Greavesy1899
License : MIT License
Project Creator : Greavesy1899
public void PopulateTranslokatorEnreplacedies()
{
for (int i = 0; i != areaDatas.Count; i++)
{
AreaData data = areaDatas[i];
for (int y = 0; y != data.Translokators.Count; y++)
{
AreaData.TranslokatorData translokator = data.Translokators[y];
if (translokator.EnreplacedyProperties == null)
{
translokator.EnreplacedyProperties = new List<short>();
for (int z = 0; z != data.Entries.Length; z++)
translokator.EnreplacedyProperties.Add(1023);
}
else if (translokator.EnreplacedyProperties.Count > data.Entries.Length)
{
List<short> temp = new List<short>();
for (int z = 0; z != data.Entries.Length - translokator.EnreplacedyProperties.Count; z++)
temp.Add(1023);
translokator.EnreplacedyProperties.AddRange(temp);
}
}
}
}
19
View Source File : EndpointList.cs
License : MIT License
Project Creator : HakanL
License : MIT License
Project Creator : HakanL
protected override void ReadData(RdmBinaryReader data)
{
ListChangeNumber = data.ReadNetwork32();
List<short> endpoints = new List<short>();
for (int n = 0; n < ((Header.ParameterDataLength-4)/2); n++)
{
endpoints.Add(data.ReadNetwork16());
}
EndpointIDs = endpoints;
}
19
View Source File : PaletteCollection.cs
License : MIT License
Project Creator : haven1433
License : MIT License
Project Creator : haven1433
public static IReadOnlyList<short> ParseColor(string stream) {
var results = new List<short>();
var parts = stream.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++) {
if (parts[i].Contains(":")) {
var channels = parts[i].Split(':');
if (channels.Length != 3) return null;
if (!int.TryParse(channels[0], out var red) || !int.TryParse(channels[1], out var green) || !int.TryParse(channels[2], out var blue)) return null;
results.Add(UncompressedPaletteColor.Pack(red, green, blue));
} else if (parts[i].Length == 4) {
if (!short.TryParse(parts[i], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var color)) return null;
results.Add(color);
} else if (parts[i].Length == 2 && i + 1 < parts.Length && parts[i + 1].Length == 2) {
if (!byte.TryParse(parts[i + 0], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var low)) return null;
if (!byte.TryParse(parts[i + 1], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var high)) return null;
i += 1;
results.Add((byte)((high << 8) | low));
} else {
return null;
}
}
return results;
}
19
View Source File : PaletteCollection.cs
License : MIT License
Project Creator : haven1433
License : MIT License
Project Creator : haven1433
public static IReadOnlyList<short> ParseColor(string stream) {
var results = new List<short>();
var parts = stream.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++) {
if (parts[i].Contains(":")) {
var channels = parts[i].Split(':');
if (channels.Length != 3) return null;
if (!int.TryParse(channels[0], out var red) || !int.TryParse(channels[1], out var green) || !int.TryParse(channels[2], out var blue)) return null;
results.Add(UncompressedPaletteColor.Pack(red, green, blue));
} else if (parts[i].Length == 4) {
if (!short.TryParse(parts[i], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var color)) return null;
results.Add(color);
} else if (parts[i].Length == 2 && i + 1 < parts.Length && parts[i + 1].Length == 2) {
if (!byte.TryParse(parts[i + 0], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var low)) return null;
if (!byte.TryParse(parts[i + 1], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var high)) return null;
i += 1;
results.Add((byte)((high << 8) | low));
} else {
return null;
}
}
return results;
}
19
View Source File : PaletteRun.cs
License : MIT License
Project Creator : haven1433
License : MIT License
Project Creator : haven1433
public static IReadOnlyList<short> GetPalette(IReadOnlyList<byte> data, int start, int count) {
var results = new List<short>();
for (int i = 0; i < count; i++) {
var color = (short)data.ReadMultiByteValue(start + i * 2, 2);
results.Add(FlipColorChannels(color));
}
return results;
}
19
View Source File : Optimizer.RegisterCleanup.cs
License : MIT License
Project Creator : JasonXuDeveloper
License : MIT License
Project Creator : JasonXuDeveloper
public static int CleanupRegister(List<OpCodeR> ins, int locRegStart, bool hasReturn)
{
short maxRegNum = (short)locRegStart;
HashSet<short> usedRegisters = new HashSet<short>();
//arguments can not be cleaned
for (short i = 0; i < locRegStart; i++)
usedRegisters.Add(i);
for (int i = 0; i < ins.Count; i++)
{
var X = ins[i];
short xSrc, xSrc2, xSrc3, xDst;
if(GetOpcodeSourceRegister(ref X, hasReturn, out xSrc, out xSrc2, out xSrc3))
{
if (xSrc >= 0)
{
if (xSrc > maxRegNum)
maxRegNum = xSrc;
usedRegisters.Add(xSrc);
}
if (xSrc2 >= 0)
{
if (xSrc2 > maxRegNum)
maxRegNum = xSrc2;
usedRegisters.Add(xSrc2);
}
if (xSrc3 >= 0)
{
if (xSrc3 > maxRegNum)
maxRegNum = xSrc3;
usedRegisters.Add(xSrc3);
}
}
if(GetOpcodeDestRegister(ref X, out xDst))
{
if (xDst >= 0)
{
if (xDst > maxRegNum)
maxRegNum = xDst;
usedRegisters.Add(xDst);
}
}
}
List<short> unusedRegisters = new List<short>();
for(short i = 0; i <= maxRegNum; i++)
{
if (!usedRegisters.Contains(i))
unusedRegisters.Add(i);
}
for(short i = 0; i < unusedRegisters.Count; i++)
{
short r = (short)(unusedRegisters[i] - i);
for (int j = 0; j < ins.Count; j++)
{
var X = ins[j];
short xSrc, xSrc2, xSrc3, xDst;
bool replaced = false;
if (GetOpcodeSourceRegister(ref X, hasReturn, out xSrc, out xSrc2, out xSrc3))
{
if (xSrc > r)
{
ReplaceOpcodeSource(ref X, 0, (short)(xSrc - 1));
replaced = true;
}
if (xSrc2 > r)
{
ReplaceOpcodeSource(ref X, 1, (short)(xSrc2 - 1));
replaced = true;
}
if (xSrc3 > r)
{
ReplaceOpcodeSource(ref X, 2, (short)(xSrc3 - 1));
replaced = true;
}
}
if (GetOpcodeDestRegister(ref X, out xDst))
{
if (xDst > r)
{
ReplaceOpcodeDest(ref X, (short)(xDst - 1));
replaced = true;
}
}
if (replaced)
ins[j] = X;
}
}
return maxRegNum - unusedRegisters.Count + 1;
}
19
View Source File : Ventana_Selector_Bloques.cs
License : GNU General Public License v3.0
Project Creator : Jupisoft111
License : GNU General Public License v3.0
Project Creator : Jupisoft111
private void Ventana_Selector_Bloques_Load(object sender, EventArgs e)
{
try
{
this.Icon = Program.Icono_Jupisoft.Clone() as Icon;
this.Text += " - [Sorry, but any change to the palette won't be saved for now...]";
//this.WindowState = FormWindowState.Maximized;
if (Lista_Paleta == null)
{
Lista_Paleta = new List<short>();
foreach (KeyValuePair<short, string> Entrada in Minecraft.Diccionario_Bloques_Índices_Nombres)
{
if (!Minecraft.Diccionario_Texturas_Transparentes.ContainsKey(Entrada.Key) && !Minecraft.Diccionario_Bloques_Altura_Diferente.ContainsKey(Entrada.Key) && !Minecraft.Diccionario_Bloques_Minecraft_1_13.ContainsKey(Entrada.Key))
{
Lista_Paleta.Add(Entrada.Key);
}
}
}
DataGridView_Principal.Rows.Clear();
//this.WindowState = FormWindowState.Maximized;
//List<byte> Lista_Bytes_CRC_32 = new List<byte>();
int Índice_Fila = 0;
DataGridViewRow[] Matriz_Filas = new DataGridViewRow[Minecraft.Diccionario_Bloques_Índices_Colores.Count];
foreach (KeyValuePair<short, Color> Entrada in Minecraft.Diccionario_Bloques_Índices_Colores)
{
string Nombre = Minecraft.Diccionario_Bloques_Índices_Nombres[Entrada.Key].Substring(10);
/*double Valor_CRC_32 = 0d;
foreach (char Caracter in Nombre)
{
Valor_CRC_32 += (double)Caracter;
}
//"".GetHashCode();
byte[] Matriz_Bytes = Encoding.UTF8.GetBytes(Nombre);
uint CRC_32 = Program.Calcular_CRC32(Matriz_Bytes);
byte CRC_8 = (byte)CRC_32;
//CRC_8 = (byte)(CRC_32 >> 24);
CRC_8 = (byte)(CRC_32 % 255);
CRC_8 = (byte)(Valor_CRC_32 % 255);
CRC_8 = (byte)(CRC_32 | (uint)Valor_CRC_32);
CRC_8 = (byte)(((double)CRC_32 + Valor_CRC_32) % 255);
CRC_8 = (byte)(Nombre.GetHashCode() % 255);
CRC_8 = (byte)Nombre.GetHashCode();
if (!Lista_Bytes_CRC_32.Contains(CRC_8)) Lista_Bytes_CRC_32.Add(CRC_8);*/
string Nombre_Invertido = null;
string[] Matriz_Palabras = Nombre.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
for (int Índice_Palabra = Matriz_Palabras.Length - 1; Índice_Palabra >= 0; Índice_Palabra--)
{
Nombre_Invertido += Matriz_Palabras[Índice_Palabra] + (Índice_Palabra > 0 ? "_" : null);
}
Nombre = Nombre.Substring(0, 1).ToUpperInvariant() + Nombre.Substring(1).Replace('_', ' ');
Nombre_Invertido = Nombre_Invertido.Substring(0, 1).ToUpperInvariant() + Nombre_Invertido.Substring(1).Replace('_', ' ');
string Tipo = null;
if (Minecraft.Diccionario_Texturas_Píxeles_Completamente_Transparentes.ContainsKey(Entrada.Key)) Tipo = "Fully transparent pixels";
else if (Minecraft.Diccionario_Texturas_Píxeles_Parcialmente_Transparentes.ContainsKey(Entrada.Key)) Tipo = "Partially transparent pixels";
else Tipo = "Solid block";
DataGridViewRow Fila = new DataGridViewRow();
Fila.CreateCells(DataGridView_Principal, new object[] { Lista_Paleta.Contains(Entrada.Key), Minecraft.Diccionario_Texturas[Entrada.Key], Nombre, Minecraft.Diccionario_Texturas[Entrada.Key], Nombre_Invertido, Program.Obtener_Imagen_Color(Color.FromArgb(Entrada.Value.A, 255, 255, 255)), Entrada.Value.A, Program.Obtener_Imagen_Color(Color.FromArgb(255, Entrada.Value.R, 0, 0)), Entrada.Value.R, Program.Obtener_Imagen_Color(Color.FromArgb(255, 0, Entrada.Value.G, 0)), Entrada.Value.G, Program.Obtener_Imagen_Color(Color.FromArgb(255, 0, 0, Entrada.Value.B)), Entrada.Value.B, Program.Obtener_Imagen_Color(Entrada.Value), /*CRC_8, */Entrada.Value.GetHashCode(), Tipo, Minecraft.Diccionario_Bloques_Índices_Nombres[Entrada.Key] });
/*Fila.Cells[Columna_Alfa.Index].Style.BackColor = Color.FromArgb(255, Entrada.Value.A, Entrada.Value.A, Entrada.Value.A);
Fila.Cells[Columna_Rojo.Index].Style.BackColor = Color.FromArgb(255, Entrada.Value.R, 0, 0);
Fila.Cells[Columna_Verde.Index].Style.BackColor = Color.FromArgb(255, 0, Entrada.Value.G, 0);
Fila.Cells[Columna_Azul.Index].Style.BackColor = Color.FromArgb(255, 0, 0, Entrada.Value.B);
Fila.Cells[Columna_Códgo_Hash.Index].Style.BackColor = Color.FromArgb(255, Entrada.Value.R, Entrada.Value.G, Entrada.Value.B);
if (Entrada.Value.A < 128) Fila.Cells[Columna_Alfa.Index].Style.ForeColor = Color.White;
if (Entrada.Value.R < 128) Fila.Cells[Columna_Rojo.Index].Style.ForeColor = Color.White;
if (Entrada.Value.G < 128) Fila.Cells[Columna_Verde.Index].Style.ForeColor = Color.White;
if (Entrada.Value.B < 128) Fila.Cells[Columna_Azul.Index].Style.ForeColor = Color.White;
if (((Entrada.Value.R + Entrada.Value.G + Entrada.Value.B) / 3) < 128) Fila.Cells[Columna_Códgo_Hash.Index].Style.ForeColor = Color.White;*/
Matriz_Filas[Índice_Fila] = Fila;
Índice_Fila++;
}
DataGridView_Principal.Rows.AddRange(Matriz_Filas);
DataGridView_Principal.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataGridView_Principal.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//MessageBox.Show(Lista_Bytes_CRC_32.Count.ToString());
}
catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); }
}
19
View Source File : SF2Chunks.cs
License : zlib License
Project Creator : Kermalis
License : zlib License
Project Creator : Kermalis
internal uint AddSample(short[] pcm16, bool bLoop, uint loopPos)
{
uint start = (uint)_samples.Count;
// Write wave
_samples.AddRange(pcm16);
// If looping is enabled, write 8 samples from the loop point
if (bLoop)
{
// In case (loopPos + i) is greater than the sample length
uint max = (uint)pcm16.Length - loopPos;
for (uint i = 0; i < 8; i++)
{
_samples.Add(pcm16[loopPos + (i % max)]);
}
}
// Write 46 empty samples
_samples.AddRange(new short[46]);
Size = (uint)_samples.Count * sizeof(short);
_sf2.UpdateSize();
return start;
}
19
View Source File : CMAP.cs
License : GNU General Public License v3.0
Project Creator : KillzXGaming
License : GNU General Public License v3.0
Project Creator : KillzXGaming
public void Read(FileReader reader, FFNT header, List<CMAP> CodeMaps)
{
uint CodeBegin = 0;
uint CodeEnd = 0;
long pos = reader.Position;
reader.ReadSignature(4, "CMAP");
SectionSize = reader.ReadUInt32();
if (header.Platform == FFNT.PlatformType.NX)
{
CodeBegin = reader.ReadUInt32();
CodeEnd = reader.ReadUInt32();
MappingMethod = reader.ReadEnum<Mapping>(true);
Padding = reader.ReadUInt16();
}
else
{
CodeBegin = reader.ReadUInt16();
CodeEnd = reader.ReadUInt16();
MappingMethod = reader.ReadEnum<Mapping>(true);
Padding = reader.ReadUInt16();
}
CharacterCodeBegin = (char)CodeBegin;
CharacterCodeEnd = (char)CodeEnd;
uint NextMapOffset = reader.ReadUInt32();
//Mapping methods from
https://github.com/IcySon55/Kuriimu/blob/f670c2719affc1eaef8b4c40e40985881247acc7/src/Cetera/Font/BFFNT.cs#L211
switch (MappingMethod)
{
case Mapping.Direct:
var charOffset = reader.ReadUInt16();
for (char i = CharacterCodeBegin; i <= CharacterCodeEnd; i++)
{
int idx = i - CharacterCodeBegin + charOffset;
header.FontSection.CodeMapDictionary[i] = idx < ushort.MaxValue ? idx : 0;
Console.WriteLine($"direct {i} {idx}");
}
MappingData = new CMAPDirect();
((CMAPDirect)MappingData).Offset = charOffset;
break;
case Mapping.Table:
List<short> table = new List<short>();
for (char i = CharacterCodeBegin; i <= CharacterCodeEnd; i++)
{
short idx = reader.ReadInt16();
if (idx != -1) header.FontSection.CodeMapDictionary[i] = idx;
Console.WriteLine($"table {i} {idx}");
table.Add(idx);
}
MappingData = new CMAPIndexTable();
((CMAPIndexTable)MappingData).Table = table.ToArray();
break;
case Mapping.Scan:
var CharEntryCount = reader.ReadUInt16();
if (header.Platform == FFNT.PlatformType.NX)
reader.ReadUInt16(); //Padding
uint[] codes = new uint[CharEntryCount];
short[] indexes = new short[CharEntryCount];
for (int i = 0; i < CharEntryCount; i++)
{
if (header.Platform == FFNT.PlatformType.NX)
{
uint charCode = reader.ReadUInt32();
short index = reader.ReadInt16();
short padding = reader.ReadInt16();
if (index != -1) header.FontSection.CodeMapDictionary[(char)charCode] = index;
codes[i] = charCode;
indexes[i] = index;
}
else
{
ushort charCode = reader.ReadUInt16();
short index = reader.ReadInt16();
if (index != -1) header.FontSection.CodeMapDictionary[(char)charCode] = index;
Console.WriteLine($"scan {i} {(char)charCode} {index}");
codes[i] = charCode;
indexes[i] = index;
}
}
MappingData = new CMAPScanMapping();
((CMAPScanMapping)MappingData).Codes = codes;
((CMAPScanMapping)MappingData).Indexes = indexes;
break;
}
if (NextMapOffset != 0)
{
reader.SeekBegin(NextMapOffset - 8);
NextCodeMapSection = new CMAP();
NextCodeMapSection.Read(reader, header, CodeMaps);
CodeMaps.Add(NextCodeMapSection);
}
else
reader.SeekBegin(pos + SectionSize);
}
19
View Source File : ImportTex.cs
License : GNU General Public License v3.0
Project Creator : liinko
License : GNU General Public License v3.0
Project Creator : liinko
private static Tuple<List<byte>, List<short>, List<short>> ReadDDS(BinaryReader br, TEXData texData, int newWidth, int newHeight, int newMipCount)
{
List<byte> compressedDDS = new List<byte>();
List<short> mipPartOffsets = new List<short>();
List<short> mipPartCount = new List<short>();
int mipLength;
if (texData.Type == TextureTypes.DXT1)
{
mipLength = (newWidth * newHeight) / 2;
}
else if (texData.Type == TextureTypes.DXT5 || texData.Type == TextureTypes.A8)
{
mipLength = newWidth * newHeight;
}
else if (texData.Type == TextureTypes.A1R5G5B5 || texData.Type == TextureTypes.A4R4G4B4)
{
mipLength = (newWidth * newHeight) * 2;
}
else
{
mipLength = (newWidth * newHeight) * 4;
}
br.BaseStream.Seek(128, SeekOrigin.Begin);
for (int i = 0; i < newMipCount; i++)
{
int mipParts = (int)Math.Ceiling(mipLength / 16000f);
mipPartCount.Add((short)mipParts);
if (mipParts > 1)
{
for (int j = 0; j < mipParts; j++)
{
int uncompLength;
byte[] compressed;
bool comp = true;
if (j == mipParts - 1)
{
uncompLength = mipLength % 16000;
}
else
{
uncompLength = 16000;
}
var uncompBytes = br.ReadBytes(uncompLength);
compressed = Compressor(uncompBytes);
if (compressed.Length > uncompLength)
{
compressed = uncompBytes;
comp = false;
}
compressedDDS.AddRange(BitConverter.GetBytes(16));
compressedDDS.AddRange(BitConverter.GetBytes(0));
if (!comp)
{
compressedDDS.AddRange(BitConverter.GetBytes(32000));
}
else
{
compressedDDS.AddRange(BitConverter.GetBytes(compressed.Length));
}
compressedDDS.AddRange(BitConverter.GetBytes(uncompLength));
compressedDDS.AddRange(compressed);
int padding = 128 - (compressed.Length % 128);
compressedDDS.AddRange(new byte[padding]);
mipPartOffsets.Add((short)(compressed.Length + padding + 16));
}
}
else
{
int uncompLength;
byte[] compressed;
bool comp = true;
if (mipLength != 16000)
{
uncompLength = mipLength % 16000;
}
else
{
uncompLength = 16000;
}
var uncompBytes = br.ReadBytes(uncompLength);
compressed = Compressor(uncompBytes);
if (compressed.Length > uncompLength)
{
compressed = uncompBytes;
comp = false;
}
compressedDDS.AddRange(BitConverter.GetBytes(16));
compressedDDS.AddRange(BitConverter.GetBytes(0));
if (!comp)
{
compressedDDS.AddRange(BitConverter.GetBytes(32000));
}
else
{
compressedDDS.AddRange(BitConverter.GetBytes(compressed.Length));
}
compressedDDS.AddRange(BitConverter.GetBytes(uncompLength));
compressedDDS.AddRange(compressed);
int padding = 128 - (compressed.Length % 128);
compressedDDS.AddRange(new byte[padding]);
mipPartOffsets.Add((short)(compressed.Length + padding + 16));
}
if (mipLength > 32)
{
mipLength = mipLength / 4;
}
else
{
mipLength = 8;
}
}
return new Tuple<List<byte>, List<short>, List<short>>(compressedDDS, mipPartOffsets, mipPartCount);
}
19
View Source File : SimpleSkinGltfExtensions.cs
License : GNU General Public License v3.0
Project Creator : LoL-Fantome
License : GNU General Public License v3.0
Project Creator : LoL-Fantome
private static Skeleton CreateLeagueSkeleton(Skin skin)
{
List<Node> nodes = new(skin.JointsCount);
for (int i = 0; i < skin.JointsCount; i++)
{
nodes.Add(skin.GetJoint(i).Joint);
}
List<SkeletonJoint> joints = new(nodes.Count);
for (int i = 0; i < nodes.Count; i++)
{
Node jointNode = nodes[i];
// If parent is null or isn't a skin joint then the joint is a root bone
if (jointNode.VisualParent is null || !jointNode.VisualParent.IsSkinJoint)
{
Vector3 scale = jointNode.LocalTransform.Scale;
joints.Add(new SkeletonJoint((short)i, -1, jointNode.Name, jointNode.LocalTransform.Translation, scale, jointNode.LocalTransform.Rotation));
}
else
{
short parentId = (short)nodes.IndexOf(jointNode.VisualParent);
joints.Add(new SkeletonJoint((short)i, parentId, jointNode.Name, jointNode.LocalTransform.Translation, jointNode.LocalTransform.Scale, jointNode.LocalTransform.Rotation));
}
}
List<short> influences = new(joints.Count);
for(short i = 0; i < joints.Count; i++)
{
influences.Add(i);
}
return new Skeleton(joints, influences);
}
19
View Source File : Skeleton.cs
License : GNU General Public License v3.0
Project Creator : LoL-Fantome
License : GNU General Public License v3.0
Project Creator : LoL-Fantome
private void ReadNew(BinaryReader br)
{
uint fileSize = br.ReadUInt32();
uint formatToken = br.ReadUInt32();
uint version = br.ReadUInt32();
if (version != 0)
{
throw new UnsupportedFileVersionException();
}
ushort flags = br.ReadUInt16();
ushort jointCount = br.ReadUInt16();
uint influencesCount = br.ReadUInt32();
int jointsOffset = br.ReadInt32();
int jointIndicesOffset = br.ReadInt32();
int influencesOffset = br.ReadInt32();
int nameOffset = br.ReadInt32();
int replacedetNameOffset = br.ReadInt32();
int boneNamesOffset = br.ReadInt32();
int reservedOffset1 = br.ReadInt32();
int reservedOffset2 = br.ReadInt32();
int reservedOffset3 = br.ReadInt32();
int reservedOffset4 = br.ReadInt32();
int reservedOffset5 = br.ReadInt32();
if (jointsOffset > 0 && jointCount != 0) //wesmart
{
br.BaseStream.Seek(jointsOffset, SeekOrigin.Begin);
for (int i = 0; i < jointCount; i++)
{
this.Joints.Add(new SkeletonJoint(br, false));
}
}
if (influencesOffset > 0 && influencesCount != 0)
{
br.BaseStream.Seek(influencesOffset, SeekOrigin.Begin);
for (int i = 0; i < influencesCount; i++)
{
this.Influences.Add(br.ReadInt16());
}
}
if (jointIndicesOffset > 0 && jointCount != 0)
{
br.BaseStream.Seek(jointIndicesOffset, SeekOrigin.Begin);
for (int i = 0; i < jointCount; i++)
{
short index = br.ReadInt16();
br.ReadInt16(); //pad
uint hash = br.ReadUInt32();
}
}
if (nameOffset > 0)
{
br.BaseStream.Seek(nameOffset, SeekOrigin.Begin);
this.Name = br.ReadZeroTerminatedString();
}
if (replacedetNameOffset > 0)
{
br.BaseStream.Seek(replacedetNameOffset, SeekOrigin.Begin);
this.replacedetName = br.ReadZeroTerminatedString();
}
}
See More Examples