module_battle_Debug.cs 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using Microsoft.Xna.Framework.Input;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Text.RegularExpressions;
  13. namespace OpenVIII
  14. {
  15. public static class Module_battle_debug
  16. {
  17. private static DeadTime DeadTime;
  18. private static Battle.RegularPyramid RegularPyramid;
  19. private static uint bs_cameraPointer;
  20. private static Matrix projectionMatrix, viewMatrix, worldMatrix;
  21. private static float degrees = 90;
  22. private static Vector3 camPosition, camTarget;
  23. private static TIM2 textureInterface;
  24. private static TextureHandler[] textures;
  25. //private static List<EnemyInstanceInformation> EnemyInstances;
  26. private static List<CharacterInstanceInformation> CharacterInstances;
  27. //skyRotating floats are hardcoded
  28. private static readonly ushort[] skyRotators = { 0x4, 0x4, 0x4, 0x4, 0x0, 0x0, 0x4, 0x4, 0x0, 0x0, 0x4, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x4, 0x4, 0x0, 0x10, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x2, 0x0, 0x0, 0x8, 0xfffc, 0xfffc, 0x0, 0x0, 0x0, 0x4, 0x0, 0x8, 0x0, 0x4, 0x4, 0x0, 0x4, 0x0, 0x4, 0xfffc, 0x8, 0xfffc, 0xfffc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x4, 0x4, 0x0, 0x0, 0x4, 0x4, 0x0, 0x0, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x4, 0x4, 0x0, 0x0, 0x4, 0x4, 0x8, 0xfffc, 0x4, 0x4, 0x4, 0x4, 0x8, 0x8, 0x4, 0xfffc, 0xfffc, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x4, 0x4, 0x4, 0x4, 0xfffc, 0x0, 0x0, 0x0, 0x0, 0x8, 0x8, 0x0, 0x8, 0xfffc, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x4, 0x4, 0x4, 0x4, 0x0, 0x0, 0x8, 0x0, 0x8, 0x8 };
  29. private static float localRotator = 0.0f; //a rotator is a float that holds current axis rotation for sky. May be malformed by skyRotators or TimeCompression magic
  30. private static BasicEffect effect;
  31. public static AlphaTestEffect ate;
  32. private static string battlename = "a0stg000.x";
  33. private static byte[] stageBuffer;
  34. private static int battleModule = 0;
  35. private static FPS_Camera fps_camera;
  36. //This should be enum btw
  37. private const int BATTLEMODULE_INIT = 0; //basic init stuff; renderer; core
  38. private const int BATTLEMODULE_READDATA = 1; //parses battle stage and all monsters
  39. private const int BATTLEMODULE_DRAWGEOMETRY = 2; //draw geometry also supports updateCamera
  40. private const int BATTLEMODULE_ACTIVE = 3;
  41. private static readonly TimeSpan FPS = TimeSpan.FromMilliseconds(1000.0d / 15d); //Natively the game we are rewritting works in 15 FPS per second
  42. /// <summary>
  43. /// controls the amount of battlecamera.time incrementation- lower value means longer camera animation
  44. /// </summary>
  45. private const int BATTLECAMERA_FRAMETIME = 3;
  46. public const int Yoffset = 0;//-10;
  47. /// <summary>
  48. /// This is helper struct that works along with VertexPosition to provide Clut, texture page
  49. /// and bool to decide if it's quad or triangle
  50. /// </summary>
  51. private struct Stage_GeometryInfoSupplier
  52. {
  53. public bool bQuad;
  54. public byte clut;
  55. public byte texPage;
  56. }
  57. public class EnemyInstanceInformation
  58. {
  59. public Debug_battleDat Data;
  60. /// <summary>
  61. /// bit position of the enemy in encounter data. Use to pair the information with
  62. /// encounter data
  63. /// </summary>
  64. public byte index;
  65. public bool bIsHidden;
  66. public bool bIsActive;
  67. public bool bIsUntargetable;
  68. public AnimationSystem animationSystem;
  69. }
  70. /// <summary>
  71. /// CharacterInstanceInformation should only be used for battle-exclusive data. Manipulating
  72. /// HP, GFs, junctions and other character-specific things should happen outside battle,
  73. /// because such information about characters is shared between almost all modules. This
  74. /// field contains information about the current status of battle rendering like animation
  75. /// frames/ rendering flags/ effects attached
  76. /// </summary>
  77. public class CharacterInstanceInformation
  78. {
  79. public CharacterData Data;
  80. public int characterId; //0 is Whatever guy
  81. public Characters VisibleCharacter => (Characters)Data.character.GetId;
  82. public bool bIsHidden; //GF sequences, magic...
  83. public AnimationSystem animationSystem;
  84. public void SetAnimationID(int id)
  85. {
  86. if (animationSystem.AnimationId != id &&
  87. id < Data.character.animHeader.animations.Length &&
  88. id < Data.weapon.animHeader.animations.Length &&
  89. id >= 0)
  90. {
  91. animationSystem.AnimationId = id;
  92. }
  93. }
  94. }
  95. private struct Triangle
  96. {
  97. public ushort A;
  98. public ushort B;
  99. public ushort C;
  100. public byte U1;
  101. public byte V1;
  102. public byte U2;
  103. public byte V2;
  104. public byte clut;
  105. public byte U3;
  106. public byte V3;
  107. public byte TexturePage;
  108. public byte bHide;
  109. public byte Red;
  110. public byte Green;
  111. public byte Blue;
  112. public byte GPU;
  113. }
  114. private struct Quad
  115. {
  116. public ushort A;
  117. public ushort B;
  118. public ushort C;
  119. public ushort D;
  120. public byte U1;
  121. public byte V1;
  122. public byte clut;
  123. public byte U2;
  124. public byte V2;
  125. public byte TexturePage;
  126. public byte bHide;
  127. public byte U3;
  128. public byte V3;
  129. public byte U4;
  130. public byte V4;
  131. public byte Red;
  132. public byte Green;
  133. public byte Blue;
  134. public byte GPU;
  135. }
  136. private struct MainGeometrySection
  137. {
  138. public uint Group1Pointer;
  139. public uint Group2Pointer;
  140. public uint Group3Pointer;
  141. public uint Group4Pointer;
  142. public uint TextureUNUSEDPointer;
  143. public uint TexturePointer;
  144. public uint EOF;
  145. }
  146. private struct ObjectsGroup
  147. {
  148. public uint numberOfSections;
  149. public uint settings1Pointer;
  150. public uint objectListPointer;
  151. public uint settings2Pointer;
  152. public uint relativeEOF;
  153. }
  154. private struct Vertex
  155. {
  156. public short X;
  157. public short Y;
  158. public short Z;
  159. }
  160. private struct Model
  161. {
  162. public Vertex[] vertices;
  163. public Triangle[] triangles;
  164. public Quad[] quads;
  165. }
  166. private struct ModelGroup
  167. {
  168. public Model[] models;
  169. }
  170. private static ModelGroup[] modelGroups;
  171. private static Debug_battleDat[] monstersData;
  172. public struct CharacterData
  173. {
  174. public Debug_battleDat character, weapon;
  175. };
  176. private static MemoryStream ms;
  177. private static BinaryReader br;
  178. private static byte GetTexturePage(byte texturepage) => (byte)(texturepage & 0x0F);
  179. private static byte GetClutId(ushort clut)
  180. {
  181. ushort bb = Extended.UshortLittleEndian(clut);
  182. return (byte)(((bb >> 14) & 0x03) | (bb << 2) & 0x0C);
  183. }
  184. public static void ResetState() => battleModule = BATTLEMODULE_INIT;
  185. public static bool PauseATB = false;
  186. private static sbyte? partypos = null;
  187. public static void Update()
  188. {
  189. DeadTime?.Update();
  190. if (CharacterInstances != null)
  191. foreach (CharacterInstanceInformation cii in CharacterInstances)
  192. {
  193. Saves.CharacterData c = Memory.State?[cii.VisibleCharacter];
  194. c.Update(); //updates ATB for Character.
  195. if (c != null && cii.animationSystem.AnimationId >= 0 && cii.animationSystem.AnimationId <= 2)
  196. {
  197. // this would probably interfeer with other animations. I am hoping the limits above will keep it good.
  198. if (c.IsDead)
  199. cii.SetAnimationID((int)AnimID.Dead);
  200. else if (c.IsCritical)
  201. cii.SetAnimationID((int)AnimID.Critical);
  202. }
  203. //if (Menu.BattleMenus.Victory_Menu.Enabled)
  204. // cii.SetAnimationID(20);
  205. //cii.SetAnimationID(31);
  206. }
  207. if (Enemy.Party != null)
  208. foreach (Enemy e in Enemy.Party)
  209. e.Update(); //updates ATB for enemy.
  210. bool ret = false;
  211. switch (battleModule)
  212. {
  213. case BATTLEMODULE_INIT:
  214. InitBattle();
  215. break;
  216. case BATTLEMODULE_READDATA:
  217. ReadData();
  218. Menu.BattleMenus.Refresh();
  219. Menu.FadeIn();
  220. break;
  221. case BATTLEMODULE_DRAWGEOMETRY:
  222. Menu.BattleMenus.Update();
  223. sbyte? partypos = Menu.BattleMenus.PartyPos;
  224. RegularPyramid.Set(GetIndicatorPoint(partypos ?? 0));
  225. if (partypos != Module_battle_debug.partypos)
  226. {
  227. if (partypos == null)
  228. {
  229. RegularPyramid.FadeOut();
  230. }
  231. else
  232. {
  233. RegularPyramid.FadeIn();
  234. }
  235. Module_battle_debug.partypos = partypos;
  236. }
  237. if (bUseFPSCamera)
  238. viewMatrix = fps_camera.Update(ref camPosition, ref camTarget, ref degrees);
  239. else
  240. {
  241. UpdateCamera();
  242. ret = Menu.BattleMenus.Inputs();
  243. }
  244. break;
  245. }
  246. if (!ret) Inputs();
  247. RegularPyramid.Update();
  248. UpdateFrames();
  249. }
  250. public static void Inputs()
  251. {
  252. #if DEBUG
  253. if (Input2.Button(Keys.D0))
  254. bUseFPSCamera = !bUseFPSCamera;
  255. if (Input2.Button(Keys.D1))
  256. if ((DEBUGframe & 0b1111) >= 7)
  257. {
  258. DEBUGframe += 0b00010000;
  259. DEBUGframe -= 7;
  260. }
  261. else DEBUGframe += 1;
  262. if (Input2.Button(Keys.D2))
  263. if ((DEBUGframe & 0b1111) == 0)
  264. {
  265. DEBUGframe -= 0b00010000;
  266. DEBUGframe += 7;
  267. }
  268. else DEBUGframe--;
  269. if (Input2.Button(Keys.D3))
  270. battleModule = BATTLEMODULE_INIT;
  271. if (Input2.Button(Keys.D4))
  272. {
  273. battleModule = BATTLEMODULE_INIT;
  274. Memory.battle_encounter++;
  275. }
  276. if (Input2.Button(Keys.D5))
  277. {
  278. AddAnimationToQueue(Debug_battleDat.EntityType.Monster, 0, 3);
  279. AddAnimationToQueue(Debug_battleDat.EntityType.Monster, 0, 0);
  280. }
  281. if (Input2.Button(Keys.F12))
  282. {
  283. if (SID < 255)
  284. SID++;
  285. else SID = 0;
  286. }
  287. if (Input2.Button(Keys.F11))
  288. {
  289. if (SID <= 0)
  290. SID = 255;
  291. else SID--;
  292. }
  293. if (Input2.Button(Keys.F10))
  294. {
  295. AddSequenceToAllQueues(SID);
  296. }
  297. if (Input2.Button(Keys.F9))
  298. {
  299. AddSequenceToAllQueues(new Debug_battleDat.AnimationSequence
  300. {
  301. AnimationQueue = new List<byte> {
  302. //0x2,
  303. //0x5,
  304. //0xf,
  305. //0x10,
  306. //0xb,
  307. //0x3,
  308. //0x6,
  309. 0xe,
  310. //0x1,
  311. 0xf,
  312. 0x0
  313. }
  314. });
  315. }
  316. if (Input2.Button(Keys.F8))
  317. {
  318. StopAnimations();
  319. }
  320. if (Input2.Button(Keys.F7))
  321. {
  322. StartAnimations();
  323. }
  324. #endif
  325. }
  326. private static void AddSequenceToAllQueues(Debug_battleDat.AnimationSequence section5)
  327. {
  328. for (int i = 0; i < Enemy.Party.Count; i++)
  329. {
  330. AddSequenceToQueue(Debug_battleDat.EntityType.Monster, i, section5);
  331. }
  332. for (int i = 0; i < CharacterInstances.Count; i++)
  333. {
  334. AddSequenceToQueue(Debug_battleDat.EntityType.Character, i, section5);
  335. }
  336. }
  337. private static void AddSequenceToAllQueues(byte sid)
  338. {
  339. Debug_battleDat.AnimationSequence section5;
  340. for (int i = 0; i < Enemy.Party.Count; i++)
  341. {
  342. if (Enemy.Party[i].EII.Data.Sequences.Count > sid)
  343. {
  344. section5 = Enemy.Party[i].EII.Data.Sequences.FirstOrDefault(x => x.id == sid);
  345. if (section5.AnimationQueue != null)
  346. AddSequenceToQueue(Debug_battleDat.EntityType.Monster, i, section5);
  347. //AddAnimationToQueue(Debug_battleDat.EntityType.Monster, i, 0);
  348. }
  349. }
  350. for (int i = 0; i < CharacterInstances.Count; i++)
  351. {
  352. Debug_battleDat weapon = CharacterInstances[i].Data.weapon;
  353. Debug_battleDat character = CharacterInstances[i].Data.character;
  354. List<Debug_battleDat.AnimationSequence> sequences;
  355. if ((weapon?.Sequences.Count ?? 0) == 0)
  356. {
  357. sequences = character.Sequences;
  358. }
  359. else sequences = weapon.Sequences;
  360. if (sequences.Count > sid)
  361. {
  362. section5 = sequences.FirstOrDefault(x => x.id == sid);
  363. if (section5.AnimationQueue != null)
  364. AddSequenceToQueue(Debug_battleDat.EntityType.Character, i, section5);
  365. //AddAnimationToQueue(Debug_battleDat.EntityType.Character, i, 0);
  366. }
  367. }
  368. }
  369. private static byte SID = 0;
  370. private static IGMDataItem.Icon CROSSHAIR { get; set; }
  371. public static void Draw()
  372. {
  373. switch (battleModule)
  374. {
  375. case BATTLEMODULE_DRAWGEOMETRY:
  376. DrawGeometry();
  377. DrawMonsters();
  378. DrawCharactersWeapons();
  379. RegularPyramid.Draw(worldMatrix, viewMatrix, projectionMatrix);
  380. //var v = Enemy.Party[0].EII.Data.VertexPositionTexturePointersGroup.VPT.Select(x => x.Position).OrderBy(x => Vector3.Distance(x, CenterOfScreen)).First();
  381. Vector3 v = GetIndicatorPoint(-1);
  382. v.Y -= 5f;
  383. //testQuad.Draw(v);
  384. if (!bUseFPSCamera)
  385. Menu.BattleMenus.Draw();
  386. break;
  387. }
  388. }
  389. public static void DrawCrosshair(Enemy enemy)
  390. {
  391. IGMData.Limit.Shot shot = Menu.BattleMenus.GetCurrentBattleMenu()?.Shot;
  392. if (shot != null && shot.Enabled)
  393. {
  394. Damageable[] targets = shot?.Targets;
  395. if (targets != null)
  396. foreach (Damageable d in targets)
  397. {
  398. if (d.GetEnemy(out Enemy e) && e.Equals(enemy))
  399. {
  400. Vector3 posIn3DSpace = e.EII.Data.IndicatorPoint;
  401. posIn3DSpace.Y -= 1f;
  402. Vector3 ScreenPos = Memory.graphics.GraphicsDevice.Viewport.Project(posIn3DSpace, ProjectionMatrix, ViewMatrix, WorldMatrix);
  403. Memory.SpriteBatchStartAlpha();
  404. CROSSHAIR.Pos = new Rectangle(new Vector2(ScreenPos.X, ScreenPos.Y).ToPoint(), Point.Zero);
  405. EntryGroup icons = Memory.Icons[CROSSHAIR.Data];
  406. TextureHandler texture = Memory.Icons.GetTexture(Icons.ID.Cross_Hair1);
  407. Vector2 s = texture.ScaleFactor;
  408. CROSSHAIR.Pos.Offset(-icons.Width * s.X / 2f, -icons.Height * s.Y / 2f);
  409. CROSSHAIR.Draw();
  410. Memory.SpriteBatchEnd();
  411. break;
  412. }
  413. }
  414. }
  415. }
  416. private static void UpdateCamera()
  417. {
  418. //const float V = 100f;
  419. //battleCamera.cam.startingTime = 64;
  420. float step = battleCamera.cam.CurrentTime.Ticks / (float)battleCamera.cam.TotalTime.Ticks;
  421. camTarget = Vector3.SmoothStep(battleCamera.cam.Camera_Lookat(0), battleCamera.cam.Camera_Lookat(1), step);
  422. camPosition = Vector3.SmoothStep(battleCamera.cam.Camera_World(0), battleCamera.cam.Camera_World(1), step);
  423. // float camWorldX = MathHelper.Lerp(battleCamera.cam.Camera_World_X_s16[0] / V,
  424. // battleCamera.cam.Camera_World_X_s16[1] / V, step) + 30;
  425. // float camWorldY = MathHelper.Lerp(battleCamera.cam.Camera_World_Y_s16[0] / V,
  426. // battleCamera.cam.Camera_World_Y_s16[1] / V, step) - 40;
  427. // float camWorldZ = MathHelper.Lerp(battleCamera.cam.Camera_World_Z_s16[0] / V,
  428. // battleCamera.cam.Camera_World_Z_s16[1] / V, step) + 0;
  429. // float camTargetX = MathHelper.Lerp(battleCamera.cam.Camera_Lookat_X_s16[0] / V,
  430. // battleCamera.cam.Camera_Lookat_X_s16[1] / V, step) + 30;
  431. // float camTargetY = MathHelper.Lerp(battleCamera.cam.Camera_Lookat_Y_s16[0] / V,
  432. //battleCamera.cam.Camera_Lookat_Y_s16[1] / V, step) - 40;
  433. // float camTargetZ = MathHelper.Lerp(battleCamera.cam.Camera_Lookat_Z_s16[0] / V,
  434. //battleCamera.cam.Camera_Lookat_Z_s16[1] / V, step) + 0;
  435. //camPosition = new Vector3(camWorldX, -camWorldY, -camWorldZ);
  436. //camTarget = new Vector3(camTargetX, -camTargetY, -camTargetZ);
  437. float fovDirector = MathHelper.SmoothStep(battleCamera.cam.startingFOV, battleCamera.cam.endingFOV, step);
  438. viewMatrix = Matrix.CreateLookAt(camPosition, camTarget,
  439. Vector3.Up);
  440. projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
  441. MathHelper.ToRadians(fovDirector / 8),
  442. Memory.graphics.GraphicsDevice.Viewport.AspectRatio,
  443. 1f, 1000f);
  444. //ate = new AlphaTestEffect(Memory.graphics.GraphicsDevice)
  445. //{
  446. // Projection = projectionMatrix,
  447. // View = viewMatrix,
  448. // World = worldMatrix
  449. //};
  450. if (battleCamera.cam.CurrentTime >= battleCamera.cam.TotalTime)
  451. {
  452. if (battleCamera.bMultiShotAnimation && battleCamera.cam.time != 0)
  453. {
  454. ReopenStageStreams();
  455. ReadAnimation(battleCamera.lastCameraPointer - 2);
  456. CloseStageStreams();
  457. }
  458. }
  459. else //battleCamera.cam.startingTime += Module_battle_debug.BATTLECAMERA_FRAMETIME;
  460. battleCamera.cam.UpdateTime();
  461. }
  462. private static void ReopenStageStreams()
  463. {
  464. ms = new MemoryStream(stageBuffer);
  465. br = new BinaryReader(ms);
  466. }
  467. private static void CloseStageStreams()
  468. {
  469. if (br != null)
  470. br.Close();
  471. if (ms != null) { ms.Close(); ms.Dispose(); }
  472. }
  473. /// <summary>
  474. /// Method to render characters and weapons for them
  475. /// </summary>
  476. private static void DrawCharactersWeapons()
  477. {
  478. Memory.graphics.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
  479. Memory.graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;
  480. Memory.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  481. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  482. ate.Projection = projectionMatrix; ate.View = viewMatrix; ate.World = worldMatrix;
  483. effect.TextureEnabled = true;
  484. //CHARACTER
  485. if (CharacterInstances == null)
  486. return;
  487. for (int n = 0; n < CharacterInstances.Count; n++)
  488. {
  489. CheckAnimationFrame(Debug_battleDat.EntityType.Character, n);
  490. Vector3 charaPosition = GetCharPos(n);
  491. DrawBattleDat(CharacterInstances[n].Data.character, CharacterInstanceGenerateStep(n), ref CharacterInstances[n].animationSystem, ref charaPosition);
  492. DrawShadow(charaPosition, ate, .5f);
  493. //WEAPON
  494. if (CharacterInstances[n].Data.weapon != null)
  495. {
  496. CheckAnimationFrame(Debug_battleDat.EntityType.Weapon, n);
  497. DrawBattleDat(CharacterInstances[n].Data.weapon, CharacterInstanceGenerateStep(n), ref CharacterInstances[n].animationSystem, ref charaPosition);
  498. }
  499. }
  500. }
  501. private static Vector3 GetCharPos(int _n) => new Vector3(-10 + _n * 10, Yoffset, -30);
  502. private static void DrawBattleDat(Debug_battleDat battledat, double step, ref AnimationSystem animationSystem, ref Vector3 position, Quaternion? _rotation = null)
  503. {
  504. for (int i = 0; /*i<1 &&*/ i < battledat.geometry.cObjects; i++)
  505. {
  506. Quaternion rotation = _rotation ?? Quaternion.CreateFromYawPitchRoll(MathHelper.Pi, 0, 0);
  507. Debug_battleDat.VertexPositionTexturePointersGRP vptpg = battledat.GetVertexPositions(
  508. i,
  509. ref position,
  510. rotation,
  511. ref animationSystem,
  512. step); //DEBUG
  513. if (vptpg.IsNotSet())
  514. return;
  515. for (int k = 0; k < vptpg.VPT.Length / 3; k++)
  516. {
  517. ate.Texture = (Texture2D)battledat.textures.textures[vptpg.TexturePointers[k]];
  518. foreach (EffectPass pass in ate.CurrentTechnique.Passes)
  519. {
  520. pass.Apply();
  521. Memory.graphics.GraphicsDevice.DrawUserPrimitives(primitiveType: PrimitiveType.TriangleList,
  522. vertexData: vptpg.VPT, vertexOffset: k * 3, primitiveCount: 1);
  523. }
  524. }
  525. }
  526. return;
  527. }
  528. private static double CharacterInstanceGenerateStep(int n) => GenerateStep(CharacterInstanceAnimationStopped(n));
  529. private static bool CharacterInstanceAnimationStopped(int n) =>
  530. CharacterInstances[n].animationSystem.AnimationStopped ||
  531. ((Memory.State?[(Characters)CharacterInstances[n].characterId]?.IsPetrify ?? false) &&
  532. CharacterInstances[n].animationSystem.StopAnimation());
  533. /// <summary>
  534. /// This function is responsible for deleting the queue of animation if passed correctly
  535. /// </summary>
  536. /// <param name="type"></param>
  537. /// <param name="n"></param>
  538. private static void CheckAnimationFrame(Debug_battleDat.EntityType type, int n)
  539. {
  540. Debug_battleDat.Animation animationSystem;
  541. switch (type)
  542. {
  543. case Debug_battleDat.EntityType.Monster:
  544. animationSystem = Enemy.Party[n].EII.Data.animHeader.animations[Enemy.Party[n].EII.animationSystem.AnimationId];
  545. if (Enemy.Party[n].EII.animationSystem.AnimationFrame >= animationSystem.cFrames)
  546. {
  547. EnemyInstanceInformation InstanceInformationProvider = Enemy.Party[n].EII;
  548. if (Enemy.Party[n].EII.animationSystem.AnimationQueue.TryDequeue(out int animid) &&
  549. animid < InstanceInformationProvider.Data.animHeader.animations.Length &&
  550. animid >= 0
  551. )
  552. {
  553. InstanceInformationProvider.animationSystem.AnimationId = animid;
  554. }
  555. Enemy.Party[n].EII = InstanceInformationProvider;
  556. }
  557. return;
  558. case Debug_battleDat.EntityType.Character:
  559. case Debug_battleDat.EntityType.Weapon:
  560. animationSystem = CharacterInstances[n].Data.character.animHeader.animations[CharacterInstances[n].animationSystem.AnimationId];
  561. if (CharacterInstances[n].animationSystem.AnimationFrame >= animationSystem.cFrames)
  562. {
  563. CharacterInstanceInformation InstanceInformationProvider = CharacterInstances[n];
  564. if (CharacterInstances[n].animationSystem.AnimationQueue.TryDequeue(out int animid) &&
  565. (animid < InstanceInformationProvider.Data.character.animHeader.animations.Length ||
  566. animid < (InstanceInformationProvider.Data.weapon?.animHeader.animations.Length ?? 0)) &&
  567. animid >= 0)
  568. {
  569. InstanceInformationProvider.animationSystem.AnimationId = animid;
  570. }
  571. CharacterInstances[n] = InstanceInformationProvider;
  572. }
  573. return;
  574. default:
  575. return;
  576. }
  577. }
  578. /// <summary>
  579. /// Animation system. Decided to go for struct, so I can attach it to instance and manipulate
  580. /// easily grouped. It's also open for modifications
  581. /// </summary>
  582. public struct AnimationSystem
  583. {
  584. public int AnimationId
  585. {
  586. get => _animationId; set
  587. {
  588. _lastAnimationId = _animationId;
  589. _animationId = value;
  590. AnimationFrame = 0;
  591. }
  592. }
  593. public int AnimationFrame
  594. {
  595. get => _animationFrame; set
  596. {
  597. _lastAnimationFrame = _animationFrame;
  598. _animationFrame = value;
  599. if (_animationFrame > 0 && _lastAnimationId != _animationId)
  600. _lastAnimationId = _animationId;
  601. }
  602. }
  603. public int NextFrame() => ++AnimationFrame;
  604. public int LastAnimationId { get => _lastAnimationId; private set => _lastAnimationId = value; }
  605. public int LastAnimationFrame { get => _lastAnimationFrame; private set => _lastAnimationFrame = value; }
  606. public bool AnimationStopped => bAnimationStopped;
  607. public bool StopAnimation()
  608. {
  609. LastAnimationFrame = AnimationFrame;
  610. AnimationId = AnimationId;
  611. return bAnimationStopped = true;
  612. }
  613. public bool StartAnimation() => bAnimationStopped = false;
  614. private bool bAnimationStopped; //pertification placeholder?
  615. public ConcurrentQueue<int> AnimationQueue;
  616. private int _lastAnimationFrame;
  617. private int _animationFrame;
  618. private int _lastAnimationId;
  619. private int _animationId;
  620. }
  621. public static int DEBUGframe = 0;
  622. private static void DrawMonsters()
  623. {
  624. Memory.graphics.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
  625. Memory.graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;
  626. Memory.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  627. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  628. ate.Projection = projectionMatrix; ate.View = viewMatrix; ate.World = worldMatrix;
  629. effect.TextureEnabled = true;
  630. if (Enemy.Party == null)
  631. return;
  632. for (int n = 0; n < Enemy.Party.Count; n++)
  633. {
  634. if (Enemy.Party[n].EII.Data.GetId == 127)
  635. {
  636. //TODO;
  637. continue;
  638. }
  639. CheckAnimationFrame(Debug_battleDat.EntityType.Monster, n);
  640. Vector3 enemyPosition = GetEnemyPos(n);
  641. enemyPosition.Y += Yoffset;
  642. DrawBattleDat(Enemy.Party[n].EII.Data, GenerateStep(EnemyInstanceAnimationStopped(n)), ref Enemy.Party[n].EII.animationSystem, ref enemyPosition, Quaternion.Identity);
  643. DrawShadow(enemyPosition, ate, Enemy.Party[n].EII.Data.skeleton.GetScale.X / 5);
  644. DrawCrosshair(Enemy.Party[n]);
  645. }
  646. }
  647. public static Vector3 GetIndicatorPoint(int n) => (n >= 0 ? CharacterInstances[n].Data.character.IndicatorPoint :
  648. Enemy.Party[-n - 1].EII.Data.IndicatorPoint) + PyramidOffset;
  649. private static Vector3 GetEnemyPos(int n) =>
  650. Memory.encounters[Memory.battle_encounter].enemyCoordinates.GetEnemyCoordinateByIndex(Enemy.Party[n].EII.index).GetVector();
  651. private static bool EnemyInstanceAnimationStopped(int n) =>
  652. Enemy.Party[n].EII.animationSystem.AnimationStopped ||
  653. (Enemy.Party[n].IsPetrify &&
  654. Enemy.Party[n].EII.animationSystem.StopAnimation());
  655. private static void StopAnimations()
  656. {
  657. foreach (CharacterInstanceInformation c in CharacterInstances)
  658. c.animationSystem.StopAnimation();
  659. foreach (Enemy e in Enemy.Party)
  660. e.EII.animationSystem.StopAnimation();
  661. }
  662. private static void StartAnimations()
  663. {
  664. foreach (CharacterInstanceInformation c in CharacterInstances)
  665. c.animationSystem.StartAnimation();
  666. foreach (Enemy e in Enemy.Party)
  667. e.EII.animationSystem.StartAnimation();
  668. }
  669. private static double GenerateStep(bool AnimationStopped)
  670. {
  671. if (AnimationStopped)
  672. return 1d;
  673. return (double)FrameTime.Ticks / FPS.Ticks;
  674. }
  675. /// <summary>
  676. /// [BROKEN] See issue #46
  677. /// </summary>
  678. /// <param name="enemyPosition"></param>
  679. /// <param name="ate"></param>
  680. /// <param name="scale"></param>
  681. private static void DrawShadow(Vector3 enemyPosition, AlphaTestEffect ate, float scale)
  682. {
  683. return;
  684. VertexPositionTexture[] ptCopy = Memory.shadowGeometry.Clone() as VertexPositionTexture[];
  685. for (int i = 0; i < ptCopy.Length; i++)
  686. ptCopy[i].Position = Vector3.Transform(ptCopy[i].Position, Matrix.CreateScale(scale));
  687. for (int i = 0; i < ptCopy.Length; i++)
  688. ptCopy[i].Position = Vector3.Add(ptCopy[i].Position, new Vector3(enemyPosition.X, 0.1f, enemyPosition.Z));
  689. ate.Texture = Memory.shadowTexture;
  690. foreach (EffectPass pass in ate.CurrentTechnique.Passes)
  691. {
  692. pass.Apply();
  693. Memory.graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, ptCopy, 0, 8);
  694. }
  695. }
  696. /// <summary>
  697. /// Increments animation frames by N, where N is equal to int(deltaTime/FPS). 15FPS is one
  698. /// frame per ~66 miliseconds. Therefore if deltaTime hits at least: below 33, then frame
  699. /// gets interpolated above 122, then frame gets skipped (by x/66)
  700. /// </summary>
  701. private static void UpdateFrames()
  702. {
  703. FrameTime += Memory.gameTime.ElapsedGameTime;
  704. if (FrameTime > FPS)
  705. {
  706. if (Enemy.Party != null)
  707. foreach (Enemy e in Enemy.Party)
  708. {
  709. if (!e.EII.animationSystem.AnimationStopped && !e.IsPetrify)
  710. e.EII.animationSystem.NextFrame();
  711. }
  712. //for (int x = 0; x < Enemy.Party.Count; x++)
  713. //{
  714. // EnemyInstanceInformation InstanceInformationProvider = Enemy.Party[x].EII;
  715. // InstanceInformationProvider.animationSystem.animationFrame++;
  716. // Enemy.Party[x].EII = InstanceInformationProvider;
  717. //}
  718. if (CharacterInstances != null)
  719. foreach (CharacterInstanceInformation cii in CharacterInstances)
  720. {
  721. if (!cii.animationSystem.AnimationStopped && (!Memory.State[cii.VisibleCharacter]?.IsPetrify ?? true))
  722. cii.animationSystem.NextFrame();
  723. }
  724. //for (int x = 0; x < CharacterInstances.Count; x++)
  725. //{
  726. // CharacterInstanceInformation InstanceInformationProvider = CharacterInstances[x];
  727. // InstanceInformationProvider.animationSystem.animationFrame++;
  728. // CharacterInstances[x] = InstanceInformationProvider;
  729. //}
  730. ResetTime();
  731. }
  732. }
  733. /// <summary>
  734. /// Plays requested animation for given entity immidiately (without waiting for current
  735. /// animation to stop if have any queued animations)
  736. /// </summary>
  737. /// <param name="entityType">Provide either Monster or Character/weapon</param>
  738. /// <param name="nIndex">
  739. /// Index of entityTypeInstance. Monster is monsterInstances, character is CharacterInstances
  740. /// </param>
  741. /// <param name="newAnimId">self explanatory</param>
  742. public static void PlayAnimationImmidiately(Debug_battleDat.EntityType entityType, int nIndex, int newAnimId)
  743. {
  744. switch (entityType)
  745. {
  746. case Debug_battleDat.EntityType.Monster:
  747. EnemyInstanceInformation MInstanceInformationProvider = Enemy.Party[nIndex].EII;
  748. MInstanceInformationProvider.animationSystem.AnimationId = newAnimId;
  749. Enemy.Party[nIndex].EII = MInstanceInformationProvider;
  750. return;
  751. case Debug_battleDat.EntityType.Character:
  752. case Debug_battleDat.EntityType.Weapon:
  753. CharacterInstanceInformation CInstanceInformationProvider = CharacterInstances[nIndex];
  754. CInstanceInformationProvider.animationSystem.AnimationId = newAnimId;
  755. CharacterInstances[nIndex] = CInstanceInformationProvider;
  756. return;
  757. default:
  758. return;
  759. }
  760. }
  761. public static void AddAnimationToQueue(Debug_battleDat.EntityType entityType, int nIndex, int newAnimId)
  762. {
  763. switch (entityType)
  764. {
  765. case Debug_battleDat.EntityType.Monster:
  766. Enemy.Party[nIndex].EII.animationSystem.AnimationQueue.Enqueue(newAnimId);
  767. return;
  768. case Debug_battleDat.EntityType.Character:
  769. case Debug_battleDat.EntityType.Weapon:
  770. CharacterInstances[nIndex].animationSystem.AnimationQueue.Enqueue(newAnimId);
  771. return;
  772. default:
  773. return;
  774. }
  775. }
  776. public static void AddSequenceToQueue(Debug_battleDat.EntityType entityType, int nIndex, Debug_battleDat.AnimationSequence section5)
  777. {
  778. foreach (byte newAnimId in section5.AnimationQueue)
  779. {
  780. AddAnimationToQueue(entityType, nIndex, newAnimId);
  781. }
  782. }
  783. //const float defaultmaxMoveSpeed = 1f;
  784. //const float MoveSpeedChange = 1f;
  785. //static float maxMoveSpeed = defaultmaxMoveSpeed;
  786. //const float maxLookSpeed = 0.25f;
  787. //public static void FPSCamera()
  788. //{
  789. // #region FPScamera
  790. // //speedcontrols
  791. // //+ to increase
  792. // //- to decrease
  793. // //* to reset
  794. // if (Input2.Button(Keys.OemPlus) || Input2.Button(Keys.Add))
  795. // {
  796. // maxMoveSpeed += MoveSpeedChange;
  797. // }
  798. // if (Input2.Button(Keys.OemMinus) || Input2.Button(Keys.Subtract))
  799. // {
  800. // maxMoveSpeed -= MoveSpeedChange;
  801. // if (maxMoveSpeed < defaultmaxMoveSpeed) maxMoveSpeed = defaultmaxMoveSpeed;
  802. // }
  803. // if (Input2.Button(Keys.Multiply)) maxMoveSpeed = defaultmaxMoveSpeed;
  804. // //speed is effected by the milliseconds between frames. so alittle goes a long way. :P
  805. // Vector2 shift = InputMouse.Distance(MouseButtons.MouseToStick, maxLookSpeed); Vector2
  806. // leftdist = InputGamePad.Distance(GamePadButtons.LeftStick, maxMoveSpeed).Abs(); shift +=
  807. // InputGamePad.Distance(GamePadButtons.RightStick, maxMoveSpeed); Yshift -= shift.Y; degrees
  808. // = (degrees + (int)shift.X) % 360; Yshift = MathHelper.Clamp(Yshift, -80, 80); if (leftdist
  809. // == Vector2.Zero) { leftdist.Y = (float)Input2.Distance(maxMoveSpeed); leftdist.X =
  810. // (float)Input2.Distance(maxMoveSpeed); }
  811. // if (Input2.Button(FF8TextTagKey.Up)) { camPosition.X +=
  812. // (float)Math.Cos(MathHelper.ToRadians(degrees)) * leftdist.Y / 10; camPosition.Z +=
  813. // (float)Math.Sin(MathHelper.ToRadians(degrees)) * leftdist.Y / 10; camPosition.Y -= Yshift
  814. // / 50; } if (Input2.Button(FF8TextTagKey.Down)) { camPosition.X -=
  815. // (float)Math.Cos(MathHelper.ToRadians(degrees)) * leftdist.Y / 10; camPosition.Z -=
  816. // (float)Math.Sin(MathHelper.ToRadians(degrees)) * leftdist.Y / 10; camPosition.Y += Yshift
  817. // / 50; } if (Input2.Button(FF8TextTagKey.Left)) { camPosition.X +=
  818. // (float)Math.Cos(MathHelper.ToRadians(degrees - 90)) * leftdist.X / 10; camPosition.Z +=
  819. // (float)Math.Sin(MathHelper.ToRadians(degrees - 90)) * leftdist.X / 10; } if
  820. // (Input2.Button(FF8TextTagKey.Right)) { camPosition.X +=
  821. // (float)Math.Cos(MathHelper.ToRadians(degrees + 90)) * leftdist.X / 10; camPosition.Z +=
  822. // (float)Math.Sin(MathHelper.ToRadians(degrees + 90)) * leftdist.X / 10; }
  823. // //Input.LockMouse();
  824. // camTarget.X = camPosition.X + (float)Math.Cos(MathHelper.ToRadians(degrees)) * camDistance;
  825. // camTarget.Z = camPosition.Z + (float)Math.Sin(MathHelper.ToRadians(degrees)) * camDistance;
  826. // camTarget.Y = camPosition.Y - Yshift / 5;
  827. // viewMatrix = Matrix.CreateLookAt(camPosition, camTarget,
  828. // Vector3.Up);
  829. // #endregion
  830. //}
  831. private static void DrawGeometry()
  832. {
  833. Memory.spriteBatch.GraphicsDevice.Clear(Color.Black);
  834. Memory.graphics.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
  835. Memory.graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;
  836. Memory.graphics.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  837. Memory.graphics.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
  838. ate.Projection = projectionMatrix; ate.View = viewMatrix; ate.World = worldMatrix;
  839. effect.TextureEnabled = true;
  840. for (int n = 0; n < modelGroups.Length; n++)
  841. foreach (Model b in modelGroups[n].models)
  842. {
  843. Tuple<Stage_GeometryInfoSupplier[], VertexPositionTexture[]> vpt = GetVertexBuffer(b);
  844. if (n == 3 && skyRotators[Memory.encounters[Memory.battle_encounter].Scenario] != 0)
  845. CreateRotation(vpt);
  846. if (vpt == null) continue;
  847. int localVertexIndex = 0;
  848. for (int i = 0; i < vpt.Item1.Length; i++)
  849. {
  850. ate.Texture = (Texture2D)textures[vpt.Item1[i].clut]; //provide texture per-face
  851. foreach (EffectPass pass in ate.CurrentTechnique.Passes)
  852. {
  853. pass.Apply();
  854. if (vpt.Item1[i].bQuad)
  855. {
  856. Memory.graphics.GraphicsDevice.DrawUserPrimitives(primitiveType: PrimitiveType.TriangleList,
  857. vertexData: vpt.Item2, vertexOffset: localVertexIndex, primitiveCount: 2);
  858. localVertexIndex += 6;
  859. }
  860. else
  861. {
  862. Memory.graphics.GraphicsDevice.DrawUserPrimitives(primitiveType: PrimitiveType.TriangleList,
  863. vertexData: vpt.Item2, vertexOffset: localVertexIndex, primitiveCount: 1);
  864. localVertexIndex += 3;
  865. }
  866. }
  867. }
  868. }
  869. Memory.SpriteBatchStartAlpha();
  870. Memory.font.RenderBasicText(new FF8String($"Encounter ready at: {Memory.battle_encounter}"), 0, 0, 1, 1, 0, 1);
  871. Memory.font.RenderBasicText(new FF8String($"Debug variable: {DEBUGframe} ({DEBUGframe >> 4},{DEBUGframe & 0b1111})"), 20, 30 * 1, 1, 1, 0, 1);
  872. if (Memory.gameTime.ElapsedGameTime.TotalMilliseconds > 0)
  873. Memory.font.RenderBasicText(new FF8String($"1000/deltaTime milliseconds: {1000 / Memory.gameTime.ElapsedGameTime.TotalMilliseconds}"), 20, 30 * 2, 1, 1, 0, 1);
  874. Memory.font.RenderBasicText(new FF8String($"camera frame: {battleCamera.cam.CurrentTime}/{battleCamera.cam.TotalTime}"), 20, 30 * 3, 1, 1, 0, 1);
  875. Memory.font.RenderBasicText(new FF8String($"Camera.World.Position: {Extended.RemoveBrackets(camPosition.ToString())}"), 20, 30 * 4, 1, 1, 0, 1);
  876. Memory.font.RenderBasicText(new FF8String($"Camera.World.Target: {Extended.RemoveBrackets(camTarget.ToString())}"), 20, 30 * 5, 1, 1, 0, 1);
  877. Memory.font.RenderBasicText(new FF8String($"Camera.FOV: {MathHelper.Lerp(battleCamera.cam.startingFOV, battleCamera.cam.endingFOV, battleCamera.cam.CurrentTime.Ticks / (float)battleCamera.cam.TotalTime.Ticks)}"), 20, 30 * 6, 1, 1, 0, 1);
  878. Memory.font.RenderBasicText(new FF8String($"Camera.Mode: {battleCamera.cam.control_word & 1}"), 20, 30 * 7, 1, 1, 0, 1);
  879. Memory.font.RenderBasicText(new FF8String($"DEBUG: Press 0 to switch between FPSCamera/Camera anim: {bUseFPSCamera}"), 20, 30 * 8, 1, 1, 0, 1);
  880. Memory.font.RenderBasicText(new FF8String($"Sequence ID: {SID}, press F10 to activate sequence, F11 SID--, F12 SID++"), 20, 30 * 9, 1, 1, 0, 1);
  881. Memory.SpriteBatchEnd();
  882. }
  883. /// <summary>
  884. /// Moves sky
  885. /// </summary>
  886. /// <param name="vpt"></param>
  887. private static void CreateRotation(Tuple<Stage_GeometryInfoSupplier[], VertexPositionTexture[]> vpt)
  888. {
  889. localRotator += (short)skyRotators[Memory.encounters[Memory.battle_encounter].Scenario] / 4096f * Memory.gameTime.ElapsedGameTime.Milliseconds;
  890. if (localRotator <= 0)
  891. return;
  892. for (int i = 0; i < vpt.Item2.Length; i++)
  893. vpt.Item2[i].Position = Vector3.Transform(vpt.Item2[i].Position, Matrix.CreateRotationY(MathHelper.ToRadians(localRotator)));
  894. }
  895. /// <summary>
  896. /// Converts requested Model data (Stage group geometry) into MonoGame VertexPositionTexture
  897. /// </summary>
  898. /// <param name="model"></param>
  899. /// <returns></returns>
  900. private static Tuple<Stage_GeometryInfoSupplier[], VertexPositionTexture[]> GetVertexBuffer(Model model)
  901. {
  902. List<VertexPositionTexture> vptDynamic = new List<VertexPositionTexture>();
  903. List<Stage_GeometryInfoSupplier> bs_renderer_supplier = new List<Stage_GeometryInfoSupplier>();
  904. if (model.vertices == null) return null;
  905. for (int i = 0; i < model.triangles.Length; i++)
  906. {
  907. Vertex A = model.vertices[model.triangles[i].A];
  908. Vertex B = model.vertices[model.triangles[i].B];
  909. Vertex C = model.vertices[model.triangles[i].C];
  910. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)A.X / 100, (float)A.Y / 100, (float)A.Z / 100),
  911. CalculateUV(model.triangles[i].U2, model.triangles[i].V2, model.triangles[i].TexturePage, textureInterface.GetWidth)));
  912. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)B.X / 100, (float)B.Y / 100, (float)B.Z / 100),
  913. CalculateUV(model.triangles[i].U3, model.triangles[i].V3, model.triangles[i].TexturePage, textureInterface.GetWidth)));
  914. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)C.X / 100, (float)C.Y / 100, (float)C.Z / 100),
  915. CalculateUV(model.triangles[i].U1, model.triangles[i].V1, model.triangles[i].TexturePage, textureInterface.GetWidth)));
  916. bs_renderer_supplier.Add(new Stage_GeometryInfoSupplier()
  917. {
  918. bQuad = false,
  919. clut = model.triangles[i].clut,
  920. texPage = model.triangles[i].TexturePage
  921. });
  922. }
  923. for (int i = 0; i < model.quads.Length; i++)
  924. {
  925. //I have to re-trangulate it. Fortunately I had been working on this lately
  926. Vertex A = model.vertices[model.quads[i].A]; //1
  927. Vertex B = model.vertices[model.quads[i].B]; //2
  928. Vertex C = model.vertices[model.quads[i].C]; //4
  929. Vertex D = model.vertices[model.quads[i].D]; //3
  930. //triangluation wing-reorder
  931. //1 2 4
  932. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)A.X / 100, (float)A.Y / 100, (float)A.Z / 100),
  933. CalculateUV(model.quads[i].U1, model.quads[i].V1, model.quads[i].TexturePage, textureInterface.GetWidth)));
  934. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)B.X / 100, (float)B.Y / 100, (float)B.Z / 100),
  935. CalculateUV(model.quads[i].U2, model.quads[i].V2, model.quads[i].TexturePage, textureInterface.GetWidth)));
  936. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)D.X / 100, (float)D.Y / 100, (float)D.Z / 100),
  937. CalculateUV(model.quads[i].U4, model.quads[i].V4, model.quads[i].TexturePage, textureInterface.GetWidth)));
  938. //1 3 4
  939. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)D.X / 100, (float)D.Y / 100, (float)D.Z / 100),
  940. CalculateUV(model.quads[i].U4, model.quads[i].V4, model.quads[i].TexturePage, textureInterface.GetWidth)));
  941. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)C.X / 100, (float)C.Y / 100, (float)C.Z / 100),
  942. CalculateUV(model.quads[i].U3, model.quads[i].V3, model.quads[i].TexturePage, textureInterface.GetWidth)));
  943. vptDynamic.Add(new VertexPositionTexture(new Vector3((float)A.X / 100, (float)A.Y / 100, (float)A.Z / 100),
  944. CalculateUV(model.quads[i].U1, model.quads[i].V1, model.quads[i].TexturePage, textureInterface.GetWidth)));
  945. bs_renderer_supplier.Add(new Stage_GeometryInfoSupplier()
  946. {
  947. bQuad = true,
  948. clut = model.quads[i].clut,
  949. texPage = model.quads[i].TexturePage
  950. });
  951. }
  952. return new Tuple<Stage_GeometryInfoSupplier[], VertexPositionTexture[]>
  953. (bs_renderer_supplier.ToArray(), vptDynamic.ToArray());
  954. }
  955. private static Vector2 CalculateUV(byte U, byte V, byte texPage, int texWidth)
  956. {
  957. //old code from my wiki page
  958. //Float U = (float)U_Byte / (float)(TIM_Texture_Width * 2) + ((float)Texture_Page / (TIM_Texture_Width * 2));
  959. float fU = (float)U / texWidth + (((float)texPage * 128) / texWidth);
  960. float fV = V / 256.0f;
  961. return new Vector2(fU, fV);
  962. }
  963. private static Vector3 PyramidOffset = new Vector3(0, 3f, 0);
  964. //private static Icons.VertexPositionTexture_Texture2D testQuad;
  965. private static void InitBattle()
  966. {
  967. CROSSHAIR = new IGMDataItem.Icon { Data = Icons.ID.Cross_Hair1 };
  968. //testQuad = Memory.Icons.Quad(Icons.ID.Cross_Hair1, 2);
  969. //MakiExtended.Debugger_Spawn();
  970. //MakiExtended.Debugger_Feed(typeof(Module_battle_debug), System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
  971. InputMouse.Mode = MouseLockMode.Center;
  972. if (DeadTime == null)
  973. {
  974. DeadTime = new DeadTime();
  975. DeadTime.DoneEvent += DeadTime_DoneEvent;
  976. }
  977. DeadTime.Restart();
  978. fps_camera = new FPS_Camera();
  979. Init_debugger_battle.Encounter enc = Memory.encounters[Memory.battle_encounter];
  980. int stage = enc.Scenario;
  981. battlename = $"a0stg{stage.ToString("000")}.x";
  982. Console.WriteLine($"BS_DEBUG: Loading stage {battlename}");
  983. Console.WriteLine($"BS_DEBUG/ENC: Encounter: {Memory.battle_encounter}\t cEnemies: {enc.EnabledEnemy}\t Enemies: {string.Join(",", enc.BEnemies.Where(x => x != 0x00).Select(x => $"{x}").ToArray())}");
  984. RegularPyramid = new Battle.RegularPyramid();
  985. RegularPyramid.Set(-2.5f, 2f, Color.Yellow);
  986. //RegularPyramid.Set(PyramidOffset);
  987. RegularPyramid.Hide();
  988. //init renderer
  989. effect = new BasicEffect(Memory.graphics.GraphicsDevice);
  990. camTarget = new Vector3(41.91198f, 33.59995f, 6.372305f);
  991. camPosition = new Vector3(40.49409f, 39.70397f, -43.321299f);
  992. projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
  993. MathHelper.ToRadians(45f),
  994. Memory.graphics.GraphicsDevice.Viewport.AspectRatio,
  995. 1f, 1000f);
  996. viewMatrix = Matrix.CreateLookAt(camPosition, camTarget,
  997. new Vector3(0f, 1f, 0f));// Y up
  998. worldMatrix = Matrix.CreateWorld(camTarget, Vector3.
  999. Forward, Vector3.Up);
  1000. battleModule++;
  1001. RasterizerState rasterizerState = new RasterizerState
  1002. {
  1003. CullMode = CullMode.None
  1004. };
  1005. ate = new AlphaTestEffect(Memory.graphics.GraphicsDevice)
  1006. {
  1007. Projection = projectionMatrix,
  1008. View = viewMatrix,
  1009. World = worldMatrix
  1010. };
  1011. return;
  1012. }
  1013. /// <summary>
  1014. /// Trigger Event when DeadTime is done.
  1015. /// </summary>
  1016. /// <param name="sender"></param>
  1017. /// <param name="e"></param>
  1018. /// <see cref="https://gamefaqs.gamespot.com/ps/197343-final-fantasy-viii/faqs/58936"/>
  1019. private static void DeadTime_DoneEvent(object sender, int e)
  1020. {
  1021. //Will Gilgamesh appear?
  1022. if (TestGilgamesh())
  1023. { }
  1024. //Will Angelo Recover be used?
  1025. else if (TestAngelo(Angelo.Recover))
  1026. { }
  1027. //Will Angelo Reverse be used?
  1028. else if (TestAngelo(Angelo.Reverse))
  1029. { }
  1030. //Will Angelo Search be used?
  1031. else if (TestAngelo(Angelo.Search))
  1032. {
  1033. //Real game has a counter that count to 255 and resets to 0
  1034. //instead of a random number. The counter counts up every 1 tick.
  1035. //60 ticks per second.
  1036. byte rnd = checked((byte)Memory.Random.Next(256));
  1037. if (rnd < 128) Algorithm(1);
  1038. else if (rnd < 160) Algorithm(2);
  1039. else if (rnd < 176) Algorithm(3);
  1040. else if (rnd < 192) Algorithm(4);
  1041. else if (rnd < 200) Algorithm(5);
  1042. else Algorithm(6);
  1043. Saves.Item Algorithm(byte i)
  1044. {
  1045. //https://gamefaqs.gamespot.com/ps/197343-final-fantasy-viii/faqs/58936
  1046. //I'm unsure where in the game files this is.
  1047. //In remaster they changed this. But unsure how
  1048. // they added (Ribbon, Friendship, and Mog's Amulet)
  1049. // using a true random kinda breaks this.
  1050. // because in game random is a set array of numbers 0-255
  1051. // so the number you get previous would determin the possible number you get
  1052. // so these can only select specific numbers. But because we are using a real random
  1053. // more items are possible. might need to tweak this.
  1054. #pragma warning disable CS0219 // Variable is assigned but its value is never used
  1055. //these are added in remaster as possible items.
  1056. const byte Ribbon = 100;
  1057. const byte Friendship = 32;
  1058. const byte Mogs_Amulet = 65;
  1059. #pragma warning restore CS0219 // Variable is assigned but its value is never used
  1060. Saves.Item item = new Saves.Item { QTY = 1 };
  1061. rnd = checked((byte)Memory.Random.Next(256));
  1062. switch (i)
  1063. {
  1064. case 1: // 1-8
  1065. item.ID = (byte)(rnd % 8 + 1);
  1066. break;
  1067. case 2: // 102-199
  1068. item.ID = (byte)(rnd % 98);
  1069. if (item.ID == 0) item.ID = 98;
  1070. item.ID += 101;
  1071. break;
  1072. case 3: // 102-124
  1073. item.ID = (byte)(rnd % 23);
  1074. if (item.ID == 0)
  1075. item.ID = 23;
  1076. item.ID += 101;
  1077. break;
  1078. case 4: // 67-100
  1079. item.ID = (byte)(rnd % 34);
  1080. if (item.ID == 0)
  1081. item.ID = 34;
  1082. item.ID += 66;
  1083. break;
  1084. case 5: // 33-54
  1085. item.ID = (byte)(rnd % 32 + 33);
  1086. break;
  1087. case 6:
  1088. default: // 33-40
  1089. item.ID = (byte)(rnd % 7 + 33);
  1090. break;
  1091. }
  1092. return item;
  1093. }
  1094. }
  1095. }
  1096. private static bool TestAngelo(Angelo ability)
  1097. {
  1098. //else if (8 >= [0..255] Angelo Recover is used (3.3 %)
  1099. //else if (2 >= [0..255] Angelo Reverse is used (1 %)
  1100. //else if (8 >= [0..255] Angelo Search is used (3.2 %)
  1101. //Angelo_Disabled I think is set when Rinoa is in space so angelo is out of reach;
  1102. //https://gamefaqs.gamespot.com/ps/197343-final-fantasy-viii/faqs/25194
  1103. if (Memory.State.BattleMISCIndicator.HasFlag(Saves.Data.MiscIndicator.Angelo_Disabled) ||
  1104. !Memory.State.PartyData.Contains(Characters.Rinoa_Heartilly) ||
  1105. !Memory.State.LimitBreakAngelocompleted.HasFlag(ability)) return false;
  1106. else
  1107. switch (ability)
  1108. {
  1109. case Angelo.Recover:
  1110. return Memory.State.Characters.Any(x => x.Value.IsCritical && !x.Value.IsDead && Memory.State.PartyData.Contains(x.Key)) && Memory.Random.Next(256) < 8;
  1111. case Angelo.Reverse:
  1112. return Memory.State.Characters.Any(x => x.Value.IsDead && Memory.State.PartyData.Contains(x.Key)) && Memory.Random.Next(256) < 2;
  1113. case Angelo.Search:
  1114. Saves.CharacterData c = Memory.State[Characters.Rinoa_Heartilly];
  1115. if (!(c.IsGameOver ||
  1116. c.Statuses1.HasFlag(Kernel_bin.Battle_Only_Statuses.Sleep) ||
  1117. c.Statuses1.HasFlag(Kernel_bin.Battle_Only_Statuses.Stop) ||
  1118. c.Statuses1.HasFlag(Kernel_bin.Battle_Only_Statuses.Confuse) ||
  1119. c.Statuses1.HasFlag(Kernel_bin.Persistent_Statuses.Berserk) ||
  1120. c.Statuses1.HasFlag(Kernel_bin.Battle_Only_Statuses.Angel_Wing)))
  1121. return Memory.Random.Next(256) < 8;
  1122. break;
  1123. }
  1124. return false;
  1125. }
  1126. private static bool TestGilgamesh() =>
  1127. //if (12 >= [0..255]) Gilgamesh is summoned (5.1 %)
  1128. Memory.State.BattleMISCIndicator.HasFlag(Saves.Data.MiscIndicator.Gilgamesh) && Memory.Random.Next(256) < 12;
  1129. #region fileParsing
  1130. private static List<Battle.Mag> MagALL;
  1131. private static IEnumerable<Battle.Mag> MagTIMs => MagALL?.Where(x => x.isTIM) ?? null;
  1132. private static IEnumerable<Battle.Mag> MagPacked => MagALL?.Where(x => x.isPackedMag) ?? null;
  1133. private static IEnumerable<Battle.Mag> MagGeometries => MagALL?.Where(x => (x.Geometries?.Count ?? 0) > 0) ?? null;
  1134. private static IEnumerable<int> MagUNKID => MagALL?.Where(x => x.UnknownType > 0).Select(x => x.UnknownType) ?? null;
  1135. private static void ReadData()
  1136. {
  1137. ArchiveWorker aw = new ArchiveWorker(Memory.Archives.A_BATTLE);
  1138. string[] test = aw.GetListOfFiles();
  1139. MagALL = new List<Battle.Mag>();
  1140. foreach (string filename in test.Where(x => x.IndexOf("mag", StringComparison.OrdinalIgnoreCase) > 0))
  1141. {
  1142. using (BinaryReader br = new BinaryReader(new MemoryStream(ArchiveWorker.GetBinaryFile(Memory.Archives.A_BATTLE, filename))))
  1143. {
  1144. Battle.Mag mag = new Battle.Mag(filename, br);
  1145. MagALL.Add(mag);
  1146. }
  1147. }
  1148. List<Battle.Mag> _MagGeo = MagGeometries.ToList();
  1149. List<Battle.Mag> _MagPack = MagPacked.ToList();
  1150. List<Battle.Mag> _MagTIM = MagTIMs.ToList();
  1151. List<int> _MagUNKID = MagUNKID.ToList();
  1152. battlename = test.First(x => x.ToLower().Contains(battlename));
  1153. string fileName = Path.GetFileNameWithoutExtension(battlename);
  1154. stageBuffer = ArchiveWorker.GetBinaryFile(Memory.Archives.A_BATTLE, battlename);
  1155. ms = new MemoryStream(stageBuffer);
  1156. br = new BinaryReader(ms);
  1157. bs_cameraPointer = GetCameraPointer();
  1158. ms.Seek(bs_cameraPointer, 0);
  1159. ReadCamera();
  1160. uint sectionCounter = br.ReadUInt32();
  1161. if (sectionCounter != 6)
  1162. {
  1163. Console.WriteLine($"BS_PARSER_PRE_OBJECTSECTION: Main geometry section has no 6 pointers at: {ms.Position}");
  1164. battleModule++;
  1165. return;
  1166. }
  1167. MainGeometrySection MainSection = ReadObjectGroupPointers();
  1168. ObjectsGroup[] objectsGroups = new ObjectsGroup[4]
  1169. {
  1170. ReadObjectsGroup(MainSection.Group1Pointer),
  1171. ReadObjectsGroup(MainSection.Group2Pointer),
  1172. ReadObjectsGroup(MainSection.Group3Pointer),
  1173. ReadObjectsGroup(MainSection.Group4Pointer)
  1174. };
  1175. modelGroups = new ModelGroup[4]
  1176. {
  1177. ReadModelGroup(objectsGroups[0].objectListPointer),
  1178. ReadModelGroup(objectsGroups[1].objectListPointer),
  1179. ReadModelGroup(objectsGroups[2].objectListPointer),
  1180. ReadModelGroup(objectsGroups[3].objectListPointer)
  1181. };
  1182. ReadTexture(MainSection.TexturePointer, fileName);
  1183. br.Close();
  1184. ms.Close();
  1185. ms.Dispose();
  1186. ReadCharacters();
  1187. ReadMonster();
  1188. battleModule++;
  1189. }
  1190. public static int DEBUG = 0;
  1191. private static TimeSpan FrameTime = TimeSpan.Zero;
  1192. private static void ResetTime() => FrameTime = TimeSpan.FromTicks(FrameTime.Ticks % FPS.Ticks);
  1193. public static ConcurrentDictionary<Characters, SortedSet<byte>> Costumes { get; private set; }
  1194. private static void FillCostumes()
  1195. {
  1196. if (Costumes == null)
  1197. {
  1198. Costumes = new ConcurrentDictionary<Characters, SortedSet<byte>>();
  1199. Regex r = new Regex(@"d([\da-fA-F]+)c(\d+)\.dat", RegexOptions.IgnoreCase);
  1200. ArchiveWorker aw = new ArchiveWorker(Memory.Archives.A_BATTLE);
  1201. foreach (string s in aw.FileList)
  1202. {
  1203. Match match = r.Match(s);
  1204. if (match != null)
  1205. {
  1206. Characters c = Characters.Blank;
  1207. if (byte.TryParse(match.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte ci))
  1208. {
  1209. c = (Characters)ci;
  1210. if (byte.TryParse(match.Groups[2].Value, out byte a))
  1211. {
  1212. Costumes.TryAdd(c, new SortedSet<byte>());
  1213. Costumes[c].Add(a);
  1214. }
  1215. }
  1216. }
  1217. }
  1218. }
  1219. }
  1220. public static ConcurrentDictionary<Characters, List<byte>> Weapons
  1221. {
  1222. get
  1223. {
  1224. FillWeapons();
  1225. return s_weapons;
  1226. }
  1227. private set => s_weapons = value;
  1228. }
  1229. public static Matrix ProjectionMatrix { get => projectionMatrix; private set => projectionMatrix = value; }
  1230. public static Matrix ViewMatrix { get => viewMatrix; private set => viewMatrix = value; }
  1231. public static Matrix WorldMatrix { get => worldMatrix; private set => worldMatrix = value; }
  1232. public static BasicEffect Effect { get => effect; private set => effect = value; }
  1233. public static Vector3 CamPosition { get => camPosition; private set => camPosition = value; }
  1234. public static Vector3 CamTarget { get => camTarget; private set => camTarget = value; }
  1235. public static Matrix CreateBillboard(Vector3 pos) => Matrix.CreateBillboard(pos, CenterOfScreen, Vector3.Up, null);
  1236. public static Matrix CreateConstrainedBillboard(Vector3 pos, Vector3 rotateAxis) => Matrix.CreateConstrainedBillboard(pos, CenterOfScreen, rotateAxis, null, null);
  1237. private static Vector3 CenterOfScreen => Memory.graphics.GraphicsDevice.Viewport.Unproject(new Vector3(Memory.graphics.GraphicsDevice.Viewport.Width / 2f, Memory.graphics.GraphicsDevice.Viewport.Height / 2f, 0f), ProjectionMatrix, ViewMatrix, WorldMatrix);
  1238. private static void FillWeapons()
  1239. {
  1240. if (s_weapons == null)
  1241. {
  1242. Weapons = new ConcurrentDictionary<Characters, List<byte>>();
  1243. for (int i = 0; i <= (int)Characters.Ward_Zabac; i++)
  1244. {
  1245. SortedSet<byte> _weapons = new SortedSet<byte>();
  1246. Regex r = new Regex(@"d(" + i.ToString("X") + @")w(\d+)\.dat", RegexOptions.IgnoreCase);
  1247. ArchiveWorker aw = new ArchiveWorker(Memory.Archives.A_BATTLE);
  1248. foreach (string s in aw.FileList.OrderBy(q => Path.GetFileName(q), StringComparer.InvariantCultureIgnoreCase))
  1249. {
  1250. Match match = r.Match(s);
  1251. if (match != null)
  1252. {
  1253. if (byte.TryParse(match.Groups[2].Value, out byte a))
  1254. {
  1255. _weapons.Add(a);
  1256. }
  1257. }
  1258. }
  1259. Weapons.TryAdd((Characters)i, _weapons.ToList());
  1260. }
  1261. }
  1262. }
  1263. /// <summary>
  1264. /// Main Animations IDs
  1265. /// </summary>
  1266. /// <remarks>more beyond this maybe part of attacking and such.</remarks>
  1267. /// <see cref="http://forums.qhimm.com/index.php?topic=19362.msg269777#msg269777"/>
  1268. private enum AnimID : int
  1269. {
  1270. Idle = 0,
  1271. Critical = 1,
  1272. Dead = 2,
  1273. //These seem to be referring to something else.
  1274. //Like he says theres another section with 30 sequences.
  1275. //where it tells how to chain the animations together.
  1276. //Damage_Taken_low_hp,
  1277. //Damage_Taken_normal,
  1278. //Damage_Taken_crit,
  1279. //Nothing,
  1280. //Appearance,
  1281. //Ready_to_Attack,
  1282. //Fail_Draw,
  1283. //Magic,
  1284. //Standing,
  1285. //Attack_normal,
  1286. //SummonGF_hide,
  1287. //Item_Use,
  1288. //Escape,
  1289. //Escaped_vanish,
  1290. //Victory,
  1291. //Becoming_Ready_to_Attack,
  1292. //SummonGF_show,
  1293. //Limit_break_normal,
  1294. //Draw_Defend_Phase_again,
  1295. //Becoming_Defend_Draw_Phase,
  1296. //Kamikaze_Command,
  1297. //Attack_Darkside,
  1298. //Escape_2,
  1299. //Defend_Draw_stock,
  1300. //Limit_break_Special,
  1301. //Defend_command_standing_again,
  1302. //Draw_Stock_Magic
  1303. }
  1304. /// <summary>
  1305. /// [WIP] Basic class responsible for creating character model into game. It should be
  1306. /// changed to be parsed from current party
  1307. /// </summary>
  1308. private static void ReadCharacters()
  1309. {
  1310. if (Memory.State?.Characters != null)
  1311. {
  1312. FillCostumes();
  1313. FillWeapons();
  1314. CharacterInstances = new List<CharacterInstanceInformation>(3);
  1315. int cid = 0;
  1316. foreach (Characters c in Memory.State.Party)
  1317. {
  1318. if (c != Characters.Blank)
  1319. {
  1320. byte weaponId = 0;
  1321. if (Memory.State.Characters.TryGetValue(c, out Saves.CharacterData characterData) &&
  1322. characterData.WeaponID < Kernel_bin.WeaponsData.Count)
  1323. {
  1324. byte altID = Kernel_bin.WeaponsData[characterData.WeaponID].AltID;
  1325. if (Weapons.TryGetValue(c, out List<byte> weapons) && weapons != null && weapons.Count > altID)
  1326. weaponId = weapons[altID];
  1327. }
  1328. CharacterInstanceInformation cii = new CharacterInstanceInformation
  1329. {
  1330. Data = ReadCharacterData((int)c,
  1331. Memory.State[c].Alternativemodel == 0 ? Costumes[c].First() : Costumes[c].Last(),
  1332. weaponId),
  1333. animationSystem = new AnimationSystem() { AnimationQueue = new ConcurrentQueue<int>() },
  1334. characterId = cid++,
  1335. };
  1336. //cii.animationSystem.animationId = 4;
  1337. Memory.State[c].BattleStart(cii);
  1338. CharacterInstances.Add(cii);
  1339. }
  1340. }
  1341. }
  1342. else
  1343. CharacterInstances = new List<CharacterInstanceInformation>
  1344. {
  1345. new CharacterInstanceInformation()
  1346. {
  1347. Data = ReadCharacterData(0,0,0),
  1348. animationSystem = new AnimationSystem(){ AnimationQueue = new ConcurrentQueue<int>()},
  1349. characterId = 0,
  1350. },
  1351. new CharacterInstanceInformation()
  1352. {
  1353. Data = ReadCharacterData(1,3,8),
  1354. animationSystem = new AnimationSystem(){ AnimationQueue = new ConcurrentQueue<int>()},
  1355. characterId = 1
  1356. },
  1357. new CharacterInstanceInformation()
  1358. {
  1359. Data = ReadCharacterData(2,6,13),
  1360. animationSystem = new AnimationSystem(){ AnimationQueue = new ConcurrentQueue<int>()},
  1361. characterId = 2
  1362. }
  1363. };
  1364. }
  1365. private static CharacterData ReadCharacterData(int characterId, int alternativeCostumeId, int weaponId)
  1366. {
  1367. Debug_battleDat character = Debug_battleDat.Load(characterId, Debug_battleDat.EntityType.Character, alternativeCostumeId);
  1368. Debug_battleDat weapon;
  1369. if (characterId == 1 || characterId == 9)
  1370. weapon = Debug_battleDat.Load(characterId, Debug_battleDat.EntityType.Weapon, weaponId, character);
  1371. #pragma warning disable IDE0045 // Convert to conditional expression
  1372. else if (weaponId != -1) weapon = Debug_battleDat.Load(characterId, Debug_battleDat.EntityType.Weapon, weaponId);
  1373. #pragma warning restore IDE0045 // Convert to conditional expression
  1374. else weapon = null;
  1375. return new CharacterData()
  1376. {
  1377. character = character,
  1378. weapon = weapon
  1379. };
  1380. }
  1381. /// <summary>
  1382. /// This method is responsible to read/parse the enemy data. It holds the result in
  1383. /// monstersData[] This method was designed to read only one instance of enemy. A list called
  1384. /// EnemyInstance holds data information for each enemy
  1385. /// </summary>
  1386. private static void ReadMonster()
  1387. {
  1388. Init_debugger_battle.Encounter enc = Memory.encounters[Memory.battle_encounter];
  1389. if (enc.EnabledEnemy == 0)
  1390. {
  1391. monstersData = new Debug_battleDat[0];
  1392. return;
  1393. }
  1394. List<byte> monstersList = enc.BEnemies.ToList();
  1395. for (int i = 7; i > 0; i--)
  1396. {
  1397. bool bEnabled = Extended.GetBit(enc.EnabledEnemy, 7 - i);
  1398. if (!bEnabled)
  1399. monstersList.RemoveLast();
  1400. }
  1401. IGrouping<byte, byte>[] DistinctMonsterPointers = monstersList.GroupBy(x => x).ToArray();
  1402. monstersData = new Debug_battleDat[DistinctMonsterPointers.Count()];
  1403. for (int n = 0; n < monstersData.Length; n++)
  1404. monstersData[n] = Debug_battleDat.Load(DistinctMonsterPointers[n].Key, Debug_battleDat.EntityType.Monster);
  1405. if (monstersData == null)
  1406. monstersData = new Debug_battleDat[0];
  1407. Enemy.Party = new List<Enemy>(8);
  1408. //EnemyInstances = new List<EnemyInstanceInformation>();
  1409. for (int i = 0; i < 8; i++)
  1410. if (Extended.GetBit(enc.EnabledEnemy, 7 - i))
  1411. Enemy.Party.Add(new EnemyInstanceInformation()
  1412. {
  1413. Data = monstersData.Where(x => x.GetId == enc.BEnemies[i]).First(),
  1414. bIsHidden = Extended.GetBit(enc.HiddenEnemies, 7 - i),
  1415. bIsActive = true,
  1416. index = (byte)(7 - i),
  1417. bIsUntargetable = Extended.GetBit(enc.UntargetableEnemy, 7 - i),
  1418. animationSystem = new AnimationSystem() { AnimationQueue = new ConcurrentQueue<int>() }
  1419. }
  1420. );
  1421. }
  1422. /// <summary>
  1423. /// Method designed for Stage texture loading.
  1424. /// </summary>
  1425. /// <param name="texturePointer">Absolute pointer to TIM texture header in stageBuffer</param>
  1426. private static void ReadTexture(uint texturePointer, string fileName)
  1427. {
  1428. textureInterface = new TIM2(stageBuffer, texturePointer);
  1429. textures = new TextureHandler[textureInterface.GetClutCount];
  1430. for (ushort i = 0; i < textureInterface.GetClutCount; i++)
  1431. textures[i] = TextureHandler.Create(fileName, textureInterface, i);
  1432. }
  1433. /// <summary>
  1434. /// Reads Stage model groups pointers and reads/parses them individually. Group0 is stage
  1435. /// ground. It's always enabled except special sequences like GFs Group1 is main geometry.
  1436. /// It's prior to Time Compression deformation Group2 is main/additional geometry. It's prior
  1437. /// to Time Compression deformation Group3 is Sky. It's NON-prior to Time Compression, but
  1438. /// may be modified by SkyRotators and/or TimeCompression last Stage skyRotation multiplier
  1439. /// </summary>
  1440. /// <param name="pointer"></param>
  1441. /// <returns></returns>
  1442. private static ModelGroup ReadModelGroup(uint pointer)
  1443. {
  1444. ms.Seek(pointer, SeekOrigin.Begin);
  1445. uint modelsCount = br.ReadUInt32();
  1446. Model[] models = new Model[modelsCount];
  1447. uint[] modelPointers = new uint[modelsCount];
  1448. for (int i = 0; i < modelsCount; i++)
  1449. modelPointers[i] = pointer + br.ReadUInt32();
  1450. for (int i = 0; i < modelsCount; i++)
  1451. models[i] = ReadModel(modelPointers[i]);
  1452. return new ModelGroup() { models = models };
  1453. }
  1454. /// <summary>
  1455. /// This is the main class that reads given Stage geometry group. It stores the data into
  1456. /// Model structure
  1457. /// </summary>
  1458. /// <param name="pointer">absolute pointer in buffer for given Stage geometry group</param>
  1459. /// <returns></returns>
  1460. private static Model ReadModel(uint pointer)
  1461. {
  1462. bool bSpecial = false;
  1463. ms.Seek(pointer, System.IO.SeekOrigin.Begin);
  1464. uint header = Extended.UintLittleEndian(br.ReadUInt32());
  1465. if (header != 0x01000100) //those may be some switches, but I don't know what they mean
  1466. {
  1467. Console.WriteLine("WARNING- THIS STAGE IS DIFFERENT! It has weird object section. INTERESTING, TO REVERSE!");
  1468. bSpecial = true;
  1469. }
  1470. ushort verticesCount = br.ReadUInt16();
  1471. Vertex[] vertices = new Vertex[verticesCount];
  1472. for (int i = 0; i < verticesCount; i++)
  1473. vertices[i] = ReadVertex();
  1474. if (bSpecial && Memory.encounters[Memory.battle_encounter].Scenario == 20)
  1475. return new Model();
  1476. ms.Seek((ms.Position % 4) + 4, SeekOrigin.Current);
  1477. ushort trianglesCount = br.ReadUInt16();
  1478. ushort quadsCount = br.ReadUInt16();
  1479. ms.Seek(4, SeekOrigin.Current);
  1480. Triangle[] triangles = new Triangle[trianglesCount];
  1481. Quad[] quads = new Quad[quadsCount];
  1482. if (trianglesCount > 0)
  1483. for (int i = 0; i < trianglesCount; i++)
  1484. triangles[i] = ReadTriangle();
  1485. if (quadsCount > 0)
  1486. for (int i = 0; i < quadsCount; i++)
  1487. quads[i] = ReadQuad();
  1488. return new Model()
  1489. {
  1490. vertices = vertices,
  1491. triangles = triangles,
  1492. quads = quads
  1493. };
  1494. }
  1495. private static Triangle ReadTriangle()
  1496. =>
  1497. new Triangle()
  1498. {
  1499. A = br.ReadUInt16(),
  1500. B = br.ReadUInt16(),
  1501. C = br.ReadUInt16(),
  1502. U1 = br.ReadByte(),
  1503. V1 = br.ReadByte(),
  1504. U2 = br.ReadByte(),
  1505. V2 = br.ReadByte(),
  1506. clut = GetClutId(br.ReadUInt16()),
  1507. U3 = br.ReadByte(),
  1508. V3 = br.ReadByte(),
  1509. TexturePage = GetTexturePage(br.ReadByte()),
  1510. bHide = br.ReadByte(),
  1511. Red = br.ReadByte(),
  1512. Green = br.ReadByte(),
  1513. Blue = br.ReadByte(),
  1514. GPU = br.ReadByte(),
  1515. };
  1516. private static Quad ReadQuad()
  1517. => new Quad()
  1518. {
  1519. A = br.ReadUInt16(),
  1520. B = br.ReadUInt16(),
  1521. C = br.ReadUInt16(),
  1522. D = br.ReadUInt16(),
  1523. U1 = br.ReadByte(),
  1524. V1 = br.ReadByte(),
  1525. clut = GetClutId(br.ReadUInt16()),
  1526. U2 = br.ReadByte(),
  1527. V2 = br.ReadByte(),
  1528. TexturePage = GetTexturePage(br.ReadByte()),
  1529. bHide = br.ReadByte(),
  1530. U3 = br.ReadByte(),
  1531. V3 = br.ReadByte(),
  1532. U4 = br.ReadByte(),
  1533. V4 = br.ReadByte(),
  1534. Red = br.ReadByte(),
  1535. Green = br.ReadByte(),
  1536. Blue = br.ReadByte(),
  1537. GPU = br.ReadByte()
  1538. };
  1539. private static Vertex ReadVertex()
  1540. => new Vertex()
  1541. {
  1542. X = br.ReadInt16(),
  1543. Y = br.ReadInt16(),
  1544. Z = br.ReadInt16(),
  1545. };
  1546. private static ObjectsGroup ReadObjectsGroup(uint pointer)
  1547. {
  1548. ms.Seek(pointer, System.IO.SeekOrigin.Begin);
  1549. return new ObjectsGroup()
  1550. {
  1551. numberOfSections = br.ReadUInt32(),
  1552. settings1Pointer = pointer + br.ReadUInt32(),
  1553. objectListPointer = pointer + br.ReadUInt32(),
  1554. settings2Pointer = pointer + br.ReadUInt32(),
  1555. relativeEOF = pointer + br.ReadUInt32(),
  1556. };
  1557. }
  1558. private static MainGeometrySection ReadObjectGroupPointers()
  1559. {
  1560. int basePointer = (int)ms.Position - 4;
  1561. uint objectGroup_1 = (uint)basePointer + br.ReadUInt32();
  1562. uint objectGroup_2 = (uint)basePointer + br.ReadUInt32();
  1563. uint objectGroup_3 = (uint)basePointer + br.ReadUInt32();
  1564. uint objectGroup_4 = (uint)basePointer + br.ReadUInt32();
  1565. uint TextureUnused = (uint)basePointer + br.ReadUInt32();
  1566. uint Texture = (uint)basePointer + br.ReadUInt32();
  1567. uint EOF = (uint)basePointer + br.ReadUInt32();
  1568. if (EOF != ms.Length)
  1569. throw new Exception("BS_PARSER_ERROR_LENGTH: Geometry EOF pointer is other than buffered filesize");
  1570. return new MainGeometrySection()
  1571. {
  1572. Group1Pointer = objectGroup_1,
  1573. Group2Pointer = objectGroup_2,
  1574. Group3Pointer = objectGroup_3,
  1575. Group4Pointer = objectGroup_4,
  1576. TextureUNUSEDPointer = TextureUnused,
  1577. TexturePointer = Texture,
  1578. EOF = EOF
  1579. }; //EOF = EOF; beauty of language
  1580. }
  1581. /// <summary>
  1582. /// Gets vanilla engine camera pointers. A team that rewrote the game into PC just left
  1583. /// PlayStation MIPS data inside files and therefore their code is to skip given hardcoded
  1584. /// data which in fact are PS compiled instructions This data is naturally read by
  1585. /// PlayStation in original console release.
  1586. /// </summary>
  1587. /// <returns>Camera pointer (data after PlayStation MIPS)</returns>
  1588. private static uint GetCameraPointer()
  1589. {
  1590. int[] _x5D4 = {4,5,9,12,13,14,15,21,22,23,24,26,
  1591. 29,32,33,34,35,36,39,40,50,53,55,61,62,63,64,65,66,67,68,69,70,
  1592. 71,72,73,75,78,82,83,85,86,87,88,89,90,91,94,96,97,98,99,100,105,
  1593. 106,121,122,123,124,125,126,127,135,138,141,144,145,148,149,150,
  1594. 151,158,160};
  1595. int[] _x5D8 = {
  1596. 0,1,2,3,6,7,10,11,17,18,25,27,28,38,41,42,43,47,49,57,58,59,60,74,
  1597. 76,77,80,81,84,93,95,101,102,103,104,109,110,111,112,113,114,115,116,
  1598. 117,118,119,120,128,129,130,131,132,133,134,139,140,143,146,152,153,154,
  1599. 155,156,159,161,162};
  1600. int _5d4 = _x5D4.Count(x => x == Memory.encounters[Memory.battle_encounter].Scenario);
  1601. int _5d8 = _x5D8.Count(x => x == Memory.encounters[Memory.battle_encounter].Scenario);
  1602. if (_5d4 > 0) return 0x5D4;
  1603. if (_5d8 > 0) return 0x5D8;
  1604. switch (Memory.encounters[Memory.battle_encounter].Scenario)
  1605. {
  1606. case 8:
  1607. case 48:
  1608. case 79:
  1609. return 0x618;
  1610. case 16:
  1611. return 0x628;
  1612. case 19:
  1613. return 0x644;
  1614. case 20:
  1615. return 0x61c;
  1616. case 30:
  1617. case 31:
  1618. return 0x934;
  1619. case 37:
  1620. return 0xcc0;
  1621. case 44:
  1622. case 45:
  1623. case 46:
  1624. return 0x9A4;
  1625. case 51:
  1626. case 52:
  1627. case 107:
  1628. case 108:
  1629. return 0x600;
  1630. case 54:
  1631. case 56:
  1632. return 0x620;
  1633. case 92:
  1634. return 0x83c;
  1635. case 136:
  1636. return 0x5fc;
  1637. case 137:
  1638. return 0xFDC;
  1639. case 142:
  1640. return 0x183C;
  1641. case 147:
  1642. return 0x10f0;
  1643. case 157:
  1644. return 0x638;
  1645. }
  1646. throw new Exception("0xFFF, unknown pointer!");
  1647. }
  1648. [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 1092)]
  1649. public struct CameraStruct
  1650. {
  1651. public byte animationId; //000
  1652. public byte keyframeCount;
  1653. public ushort control_word;
  1654. public ushort startingFOV; //usually ~280
  1655. public ushort endingFOV; //006
  1656. public ushort startingCameraRoll; //usually 0 unless you're aiming for some wicked animation
  1657. public ushort endingCameraRoll; //
  1658. private ushort startingTime; //usually 0, that's pretty logical
  1659. /// <summary>
  1660. /// Time is calculated from number of frames. You basically set starting position
  1661. /// World+lookat and ending position, then mark number of frames to interpolate between
  1662. /// them. Every frame is one drawcall and it costs 16.
  1663. /// </summary>
  1664. public ushort time; //starting time needs to be equal or higher for next animation frame to be read; If next frame==0xFFFF then it's all done
  1665. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
  1666. public byte[] unk; //010
  1667. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1668. public ushort[] startFramesOffsets; //024 - start frames for each key frame?
  1669. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1670. public short[] Camera_World_Z_s16; //064
  1671. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1672. public short[] Camera_World_X_s16; //0A4
  1673. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1674. public short[] Camera_World_Y_s16; //0E4
  1675. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1676. public byte[] is_FrameDurationsShot; //124
  1677. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1678. public short[] Camera_Lookat_Z_s16; //144
  1679. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1680. public short[] Camera_Lookat_X_s16; //184
  1681. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1682. public short[] Camera_Lookat_Y_s16; //1C4
  1683. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  1684. public byte[] is_FrameEndingShots; //204
  1685. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  1686. public byte[] unkbyte224; //224
  1687. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  1688. public byte[] unkbyte2A4; //2A4
  1689. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  1690. public byte[] unkbyte324; //324
  1691. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  1692. public byte[] unkbyte3A4; //3A4
  1693. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  1694. public byte[] unkbyte424; //424
  1695. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  1696. public byte[] unkbyte4A4; //4A4
  1697. private const float V = 100f;
  1698. private Vector3 offset => new Vector3(30, +40, 0);
  1699. public Vector3 Camera_World(int i) => new Vector3(
  1700. Camera_World_X_s16[i] / V,
  1701. -(Camera_World_Y_s16[i] / V),
  1702. -(Camera_World_Z_s16[i] / V)) + offset;
  1703. public Vector3 Camera_Lookat(int i) => new Vector3(
  1704. Camera_Lookat_X_s16[i] / V,
  1705. -(Camera_Lookat_Y_s16[i] / V),
  1706. -(Camera_Lookat_Z_s16[i] / V)) + offset;
  1707. public void UpdateTime() => CurrentTime += Memory.gameTime.ElapsedGameTime;
  1708. public TimeSpan CurrentTime;
  1709. public TimeSpan TotalTime => TimeSpan.FromTicks(TotalTimePerFrame.Ticks * time);
  1710. /// <summary>
  1711. /// (1000) milliseconds / frames per second
  1712. /// </summary>
  1713. public TimeSpan TotalTimePerFrame => TimeSpan.FromMilliseconds(1000d / 240d);
  1714. };
  1715. /// <summary>
  1716. /// Main battle camera struct. It holds data for camera settings, camera collections and main
  1717. /// CameraStruct used as a final result of camera parsing
  1718. /// </summary>
  1719. private struct BattleCamera
  1720. {
  1721. public BattleCameraSettings battleCameraSettings;
  1722. public BattleCameraCollection battleCameraCollection;
  1723. public CameraStruct cam;
  1724. public uint lastCameraPointer;
  1725. public bool bMultiShotAnimation;
  1726. }
  1727. private static BattleCamera battleCamera;
  1728. private static bool bUseFPSCamera = false;
  1729. private static ConcurrentDictionary<Characters, List<byte>> s_weapons;
  1730. /// <summary>
  1731. /// Battle camera settings are about 32 bytes of unknown flags and variables used in whole
  1732. /// stage including geometry
  1733. /// </summary>
  1734. private struct BattleCameraSettings
  1735. {
  1736. public byte[] unk;
  1737. }
  1738. /// <summary>
  1739. /// Main struct for collection of camera animations. Every BattleCameraSet hold 8 animations
  1740. /// no matter what
  1741. /// </summary>
  1742. private struct BattleCameraCollection
  1743. {
  1744. public uint cAnimCollectionCount;
  1745. public uint pCameraEOF;
  1746. public BattleCameraSet[] battleCameraSet;
  1747. }
  1748. /// <summary>
  1749. /// Struct for battle camera animation set. Animation set always contain 8 animations. This
  1750. /// struct does not contain a data for pre-readed information. Therefore you have to call
  1751. /// ReadAnimation(index) to actually read the animation to BattleCamera.cam(CameraStruct).
  1752. /// That is because there are extreme amount of cases where the camera is changing and
  1753. /// reading again and again not including the battle stage. Also reading all camera
  1754. /// animations is waste of time and resources
  1755. /// </summary>
  1756. private struct BattleCameraSet
  1757. {
  1758. public uint[] animPointers;
  1759. public uint globalSetPointer;
  1760. }
  1761. /// <summary>
  1762. /// Parses camera data into BattleCamera struct. Main purpouse of this function is to
  1763. /// actually read all the offsets and pointers to human readable form of struct. This
  1764. /// function later calls ReadAnimation(n) where n is animation Id (i.e. 9 is camCollection=1
  1765. /// and cameraAnim=0)
  1766. /// </summary>
  1767. private static void ReadCamera()
  1768. {
  1769. uint cCameraHeaderSector = br.ReadUInt16();
  1770. uint pCameraSetting = br.ReadUInt16();
  1771. uint pCameraAnimationCollection = br.ReadUInt16();
  1772. uint sCameraDataSize = br.ReadUInt16();
  1773. //Camera settings parsing?
  1774. BattleCameraSettings bcs = new BattleCameraSettings() { unk = br.ReadBytes(24) };
  1775. //end of camera settings parsing
  1776. ms.Seek(bs_cameraPointer, 0);
  1777. ms.Seek(pCameraAnimationCollection, SeekOrigin.Current);
  1778. BattleCameraCollection bcc = new BattleCameraCollection { cAnimCollectionCount = br.ReadUInt16() };
  1779. BattleCameraSet[] bcset = new BattleCameraSet[bcc.cAnimCollectionCount];
  1780. bcc.battleCameraSet = bcset;
  1781. for (int i = 0; i < bcc.cAnimCollectionCount; i++)
  1782. bcset[i] = new BattleCameraSet() { globalSetPointer = (uint)(ms.Position + br.ReadUInt16() - i * 2 - 2) };
  1783. bcc.pCameraEOF = br.ReadUInt16();
  1784. for (int i = 0; i < bcc.cAnimCollectionCount; i++)
  1785. {
  1786. ms.Seek(bcc.battleCameraSet[i].globalSetPointer, 0);
  1787. bcc.battleCameraSet[i].animPointers = new uint[8];
  1788. for (int n = 0; n < bcc.battleCameraSet[i].animPointers.Length; n++)
  1789. bcc.battleCameraSet[i].animPointers[n] = (uint)(ms.Position + br.ReadUInt16() * 2 - n * 2);
  1790. }
  1791. CameraStruct cam = Extended.ByteArrayToStructure<CameraStruct>(new byte[Marshal.SizeOf(typeof(CameraStruct))]); //what about this kind of trick to initialize struct with a lot amount of fixed sizes in arrays?
  1792. battleCamera = new BattleCamera() { battleCameraCollection = bcc, battleCameraSettings = bcs, cam = cam };
  1793. ReadAnimationById(GetRandomCameraN(Memory.encounters[Memory.battle_encounter]));
  1794. ms.Seek(bs_cameraPointer + sCameraDataSize, 0); //step out
  1795. }
  1796. /// <summary>
  1797. /// Gets random camera from available from encounter- primary or secondary
  1798. /// </summary>
  1799. /// <param name="encounter">instance of current encounter</param>
  1800. /// <returns>Either primary or alternative camera from encounter</returns>
  1801. private static byte GetRandomCameraN(Init_debugger_battle.Encounter encounter)
  1802. {
  1803. int camToss = Memory.Random.Next(3) < 2 ? 0 : 1; //primary camera has 2/3 chance of beign selected
  1804. switch (camToss)
  1805. {
  1806. case 0:
  1807. return encounter.PrimaryCamera;
  1808. case 1:
  1809. return encounter.AlternativeCamera;
  1810. default:
  1811. goto case 0;
  1812. }
  1813. }
  1814. private struct CameraSetAnimGRP
  1815. {
  1816. public int Set { get; private set; }
  1817. public int Anim { get; private set; }
  1818. public CameraSetAnimGRP(int set, int anim)
  1819. {
  1820. Set = set;
  1821. Anim = anim;
  1822. }
  1823. }
  1824. /// <summary>
  1825. /// Returns tuple containing camera animation set pointer and camera animation in that set
  1826. /// </summary>
  1827. /// <param name="animId">6bit variable containing camera pointer</param>
  1828. /// <returns>Tuple with CameraSetPointer, CameraSetPointer[CameraAnimationPointer]</returns>
  1829. private static CameraSetAnimGRP GetCameraCollectionPointers(byte animId)
  1830. {
  1831. Init_debugger_battle.Encounter enc = Memory.encounters[Memory.battle_encounter];
  1832. int pSet = enc.ResolveCameraSet(animId);
  1833. int pAnim = enc.ResolveCameraAnimation(animId);
  1834. return new CameraSetAnimGRP(pSet, pAnim);
  1835. }
  1836. /// <summary>
  1837. /// This method resolves the correct camera pointer and runs ReadAnimation(uint,ms,br) method
  1838. /// and returns the final pointer
  1839. /// </summary>
  1840. /// <param name="animId">
  1841. /// Animation Id as of binary mask (0bXXXXYYYY where XXXX= animationSet and YYYY=animationId)
  1842. /// </param>
  1843. /// <returns></returns>
  1844. private static uint ReadAnimationById(byte animId)
  1845. {
  1846. animId = (byte)DEBUGframe; //DEBUG
  1847. CameraSetAnimGRP tpGetter = GetCameraCollectionPointers(animId);
  1848. BattleCameraSet[] battleCameraSetArray = battleCamera.battleCameraCollection.battleCameraSet;
  1849. if (battleCameraSetArray.Length > tpGetter.Set && battleCameraSetArray[tpGetter.Set].animPointers.Length > tpGetter.Anim)
  1850. {
  1851. BattleCameraSet battleCameraSet = battleCameraSetArray[tpGetter.Set];
  1852. uint cameraAnimationGlobalPointer = battleCameraSet.animPointers[tpGetter.Anim];
  1853. return ReadAnimation(cameraAnimationGlobalPointer);
  1854. }
  1855. else
  1856. {
  1857. Debug.WriteLine($"ReadAnimationById::{battleCameraSetArray.Length} < {tpGetter.Set}");
  1858. if (battleCameraSetArray.Length > tpGetter.Set)
  1859. Debug.WriteLine($" or \n{battleCameraSetArray[tpGetter.Set].animPointers.Length} < {tpGetter.Anim}");
  1860. }
  1861. return 0;
  1862. }
  1863. /// <summary>
  1864. /// This method reads raw animation data in stage file or if ms_ and br_ == null then ms_
  1865. /// file and stores parsed data into battleCamera struct
  1866. /// </summary>
  1867. /// <param name="cameraAnimOffset">
  1868. /// if (ms_ and br_ are null) is an offset in current battle stage file for camera animation.
  1869. /// If ms_ and _br are provided it's the offset in this file
  1870. /// </param>
  1871. /// <param name="ms_">if null then stage file either this memory stream</param>
  1872. /// <param name="br_">sub-component of ms</param>
  1873. /// <remarks See also = BS_Camera_ReadAnimation - 00503AC0></remarks>
  1874. /// <returns></returns>
  1875. private static uint ReadAnimation(uint cameraAnimOffset, MemoryStream ms_ = null, BinaryReader br_ = null)
  1876. {
  1877. if (ms_ == null || br_ == null)
  1878. { ms_ = ms; br_ = br; }
  1879. short local2C;
  1880. byte keyframecount = 0;
  1881. ushort totalframecount = 0;
  1882. short local1C;
  1883. short local18;
  1884. short local14;
  1885. short local10;
  1886. ms_.Seek(cameraAnimOffset, SeekOrigin.Begin);
  1887. battleCamera.cam.control_word = br_.ReadUInt16();
  1888. if (battleCamera.cam.control_word == 0xFFFF)
  1889. return 0; //return NULL
  1890. ushort current_position = br_.ReadUInt16(); //getter for *current_position
  1891. ms_.Seek(-2, SeekOrigin.Current); //roll back one WORD because no increment
  1892. switch ((battleCamera.cam.control_word >> 6) & 3)
  1893. {
  1894. case 1:
  1895. battleCamera.cam.startingFOV = 0x200;
  1896. battleCamera.cam.endingFOV = 0x200;
  1897. break;
  1898. case 2:
  1899. battleCamera.cam.startingFOV = current_position;
  1900. battleCamera.cam.endingFOV = current_position;
  1901. br_.ReadUInt16(); //current_position++
  1902. break;
  1903. case 3:
  1904. battleCamera.cam.startingFOV = current_position;
  1905. ms_.Seek(2, SeekOrigin.Current); //skipping WORD, because we already rolled back one WORD above this switch
  1906. current_position = br_.ReadUInt16();
  1907. battleCamera.cam.endingFOV = current_position;
  1908. break;
  1909. }
  1910. switch ((battleCamera.cam.control_word >> 8) & 3)
  1911. {
  1912. case 0: //TODO!!
  1913. battleCamera.cam.startingCameraRoll = 00000000; //TODO, what's ff8vars.unkword1D977A2?
  1914. battleCamera.cam.endingCameraRoll = 00000000; //same as above; cam->unkword00A = ff8vars.unkword1D977A2;
  1915. break;
  1916. case 1:
  1917. battleCamera.cam.startingCameraRoll = 0;
  1918. battleCamera.cam.endingCameraRoll = 0;
  1919. break;
  1920. case 2:
  1921. current_position = br_.ReadUInt16(); //* + current_position++;
  1922. battleCamera.cam.startingCameraRoll = current_position;
  1923. battleCamera.cam.endingCameraRoll = current_position;
  1924. break;
  1925. case 3:
  1926. current_position = br_.ReadUInt16(); //* + current_position++;
  1927. battleCamera.cam.startingCameraRoll = current_position;
  1928. current_position = br_.ReadUInt16(); //* + current_position++;
  1929. battleCamera.cam.endingCameraRoll = current_position;
  1930. break;
  1931. }
  1932. switch (battleCamera.cam.control_word & 1)
  1933. {
  1934. case 0:
  1935. if (current_position >= 0)
  1936. {
  1937. while (true) //I'm setting this to true and breaking in code as this works on peeking on next variable via pointer and that's not possible here without unsafe block
  1938. {
  1939. battleCamera.cam.startFramesOffsets[keyframecount] = totalframecount; //looks like this is the camera index
  1940. current_position = br_.ReadUInt16();
  1941. if ((short)current_position < 0) //reverse of *current_position >= 0, also cast to signed is important here
  1942. break;
  1943. totalframecount += (ushort)(current_position * 16); //here is increment of short*, but I already did that above
  1944. battleCamera.cam.is_FrameDurationsShot[keyframecount] = (byte)(current_position = br_.ReadUInt16()); //cam->unkbyte124[keyframecount] = *current_position++; - looks like we are wasting one byte due to integer sizes
  1945. battleCamera.cam.Camera_World_X_s16[keyframecount] = (short)(current_position = br_.ReadUInt16());
  1946. battleCamera.cam.Camera_World_Y_s16[keyframecount] = (short)(current_position = br_.ReadUInt16());
  1947. battleCamera.cam.Camera_World_Z_s16[keyframecount] = (short)(current_position = br_.ReadUInt16());
  1948. battleCamera.cam.is_FrameEndingShots[keyframecount] = (byte)(current_position = br_.ReadUInt16()); //m->unkbyte204[keyframecount] = *current_position++;
  1949. battleCamera.cam.Camera_Lookat_X_s16[keyframecount] = (short)(current_position = br_.ReadUInt16());
  1950. battleCamera.cam.Camera_Lookat_Y_s16[keyframecount] = (short)(current_position = br_.ReadUInt16());
  1951. battleCamera.cam.Camera_Lookat_Z_s16[keyframecount] = (short)(current_position = br_.ReadUInt16());
  1952. keyframecount++;
  1953. }
  1954. if (keyframecount > 2)
  1955. {
  1956. //ff8funcs.Sub50D010(cam->unkword024, cam->unkword064, cam->unkword0A4, cam->unkword0E4, keyframecount, cam->unkbyte224, cam->unkbyte2A4, cam->unkbyte324);
  1957. //ff8funcs.Sub50D010(cam->unkword024, cam->unkword144, cam->unkword184, cam->unkword1C4, keyframecount, cam->unkbyte3A4, cam->unkbyte424, cam->unkbyte4A4);
  1958. }
  1959. }
  1960. break;
  1961. case 1:
  1962. {
  1963. goto case 0;
  1964. if (current_position >= 0)
  1965. {
  1966. local14 = (short)(ms_.Position + 5 * 2); //current_position + 5; but current_position is WORD, so multiply by two
  1967. local10 = (short)(ms_.Position + 6 * 2);
  1968. local2C = (short)(ms_.Position + 7 * 2);
  1969. local18 = (short)(ms_.Position + 1 * 2);
  1970. local1C = (short)(ms_.Position + 2 * 2);
  1971. while (true)
  1972. {
  1973. battleCamera.cam.startFramesOffsets[keyframecount] = totalframecount;
  1974. current_position = br_.ReadUInt16();
  1975. if ((short)current_position < 0) //reverse of *current_position >= 0, also cast to signed is important here
  1976. break;
  1977. totalframecount += (ushort)(current_position * 16);
  1978. //ff8funcs.Sub503AE0(++local18, ++local1C, ++ebx, *(BYTE*)current_position, &cam->unkword064[keyframecount], &cam->unkword0A4[keyframecount], &cam->unkword0E4[keyframecount]);
  1979. //ff8funcs.Sub503AE0(++local14, ++local10, ++local2C, *(BYTE*)(current_position + 4), &cam->unkword144[keyframecount], &cam->unkword184[keyframecount], &cam->unkword1C4[keyframecount]);
  1980. battleCamera.cam.is_FrameEndingShots[keyframecount] = 0xFB;
  1981. battleCamera.cam.is_FrameDurationsShot[keyframecount] = 0xFB;
  1982. local1C += 8;
  1983. local18 += 8;
  1984. current_position += 8;
  1985. local2C += 8;
  1986. //ebx += 8;
  1987. local10 += 8;
  1988. local14 += 8;
  1989. keyframecount++;
  1990. }
  1991. }
  1992. break;
  1993. }
  1994. }
  1995. if ((battleCamera.cam.control_word & 0x3E) == 0x1E)
  1996. {
  1997. //ff8funcs.Sub503300();
  1998. }
  1999. battleCamera.cam.keyframeCount = keyframecount;
  2000. battleCamera.cam.time = totalframecount;
  2001. //battleCamera.cam.startingTime = 0;
  2002. battleCamera.cam.CurrentTime = TimeSpan.Zero;
  2003. battleCamera.lastCameraPointer = (uint)(ms_.Position + 2);
  2004. battleCamera.bMultiShotAnimation = br.ReadInt16() != -1;
  2005. return (uint)(ms_.Position);
  2006. }
  2007. #endregion fileParsing
  2008. }
  2009. }