A stable modding interface between Techblox and mods https://mod.exmods.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

429 lines
14KB

  1. using System;
  2. using Svelto.ECS;
  3. using Svelto.DataStructures;
  4. using Gamecraft.Wires;
  5. using TechbloxModdingAPI.Engines;
  6. namespace TechbloxModdingAPI.Blocks
  7. {
  8. /// <summary>
  9. /// Engine which executes signal actions
  10. /// </summary>
  11. public class SignalEngine : IApiEngine, IFactoryEngine
  12. {
  13. public const float POSITIVE_HIGH = 1.0f;
  14. public const float NEGATIVE_HIGH = -1.0f;
  15. public const float HIGH = 1.0f;
  16. public const float ZERO = 0.0f;
  17. public string Name { get; } = "TechbloxModdingAPISignalGameEngine";
  18. public EntitiesDB entitiesDB { set; private get; }
  19. public IEntityFactory Factory { get; set; }
  20. public bool isRemovable => false;
  21. public bool IsInGame = false;
  22. public void Dispose()
  23. {
  24. IsInGame = false;
  25. }
  26. public void Ready()
  27. {
  28. IsInGame = true;
  29. }
  30. // implementations for block wiring
  31. public WireEntityStruct CreateNewWire(EGID startBlock, byte startPort, EGID endBlock, byte endPort)
  32. {
  33. EGID wireEGID = new EGID(WiresExclusiveGroups.NewWireEntityId, NamedExclusiveGroup<WiresGroup>.Group);
  34. EntityInitializer wireInitializer = Factory.BuildEntity<WireEntityDescriptor>(wireEGID);
  35. wireInitializer.Init(new WireEntityStruct
  36. {
  37. sourceBlockEGID = startBlock,
  38. sourcePortUsage = startPort,
  39. destinationBlockEGID = endBlock,
  40. destinationPortUsage = endPort,
  41. ID = wireEGID
  42. });
  43. return wireInitializer.Get<WireEntityStruct>();
  44. }
  45. public ref WireEntityStruct GetWire(EGID wire)
  46. {
  47. if (!entitiesDB.Exists<WireEntityStruct>(wire))
  48. {
  49. throw new WiringException($"Wire {wire} does not exist");
  50. }
  51. return ref entitiesDB.QueryEntity<WireEntityStruct>(wire);
  52. }
  53. public ref PortEntityStruct GetPort(EGID port)
  54. {
  55. if (!entitiesDB.Exists<PortEntityStruct>(port))
  56. {
  57. throw new WiringException($"Port {port} does not exist (yet?)");
  58. }
  59. return ref entitiesDB.QueryEntity<PortEntityStruct>(port);
  60. }
  61. public ref PortEntityStruct GetPortByOffset(BlockPortsStruct bps, byte portNumber, bool input)
  62. {
  63. ExclusiveGroup group = input
  64. ? NamedExclusiveGroup<InputPortsGroup>.Group
  65. : NamedExclusiveGroup<OutputPortsGroup>.Group;
  66. uint id = (input ? bps.firstInputID : bps.firstOutputID) + portNumber;
  67. EGID egid = new EGID(id, group);
  68. if (!entitiesDB.Exists<PortEntityStruct>(egid))
  69. {
  70. throw new WiringException("Port does not exist");
  71. }
  72. return ref entitiesDB.QueryEntity<PortEntityStruct>(egid);
  73. }
  74. public ref PortEntityStruct GetPortByOffset(Block block, byte portNumber, bool input)
  75. {
  76. BlockPortsStruct bps = GetFromDbOrInitData<BlockPortsStruct>(block, block.Id, out bool exists);
  77. if (!exists)
  78. {
  79. throw new BlockException("Block does not exist");
  80. }
  81. return ref GetPortByOffset(bps, portNumber, input);
  82. }
  83. public ref T GetComponent<T>(EGID egid) where T : unmanaged, IEntityComponent
  84. {
  85. return ref entitiesDB.QueryEntity<T>(egid);
  86. }
  87. public bool Exists<T>(EGID egid) where T : struct, IEntityComponent
  88. {
  89. return entitiesDB.Exists<T>(egid);
  90. }
  91. public bool SetSignal(EGID blockID, float signal, out uint signalID, bool input = true)
  92. {
  93. signalID = GetSignalIDs(blockID, input)[0];
  94. return SetSignal(signalID, signal);
  95. }
  96. public bool SetSignal(uint signalID, float signal, bool input = true)
  97. {
  98. var array = GetSignalStruct(signalID, out uint index, input);
  99. var arrayB = array.ToBuffer();
  100. if (array.count > 0) arrayB.buffer[index].valueAsFloat = signal;
  101. return false;
  102. }
  103. public float AddSignal(EGID blockID, float signal, out uint signalID, bool clamp = true, bool input = true)
  104. {
  105. signalID = GetSignalIDs(blockID, input)[0];
  106. return AddSignal(signalID, signal, clamp, input);
  107. }
  108. public float AddSignal(uint signalID, float signal, bool clamp = true, bool input = true)
  109. {
  110. var array = GetSignalStruct(signalID, out uint index, input);
  111. var arrayB = array.ToBuffer();
  112. if (array.count > 0)
  113. {
  114. ref var channelData = ref arrayB.buffer[index];
  115. channelData.valueAsFloat += signal;
  116. if (clamp)
  117. {
  118. if (channelData.valueAsFloat > POSITIVE_HIGH)
  119. {
  120. channelData.valueAsFloat = POSITIVE_HIGH;
  121. }
  122. else if (channelData.valueAsFloat < NEGATIVE_HIGH)
  123. {
  124. channelData.valueAsFloat = NEGATIVE_HIGH;
  125. }
  126. return channelData.valueAsFloat;
  127. }
  128. }
  129. return signal;
  130. }
  131. public float GetSignal(EGID blockID, out uint signalID, bool input = true)
  132. {
  133. signalID = GetSignalIDs(blockID, input)[0];
  134. return GetSignal(signalID, input);
  135. }
  136. public float GetSignal(uint signalID, bool input = true)
  137. {
  138. var array = GetSignalStruct(signalID, out uint index, input);
  139. var arrayB = array.ToBuffer();
  140. return array.count > 0 ? arrayB.buffer[index].valueAsFloat : 0f;
  141. }
  142. public uint[] GetSignalIDs(EGID blockID, bool input = true)
  143. {
  144. ref BlockPortsStruct bps = ref entitiesDB.QueryEntity<BlockPortsStruct>(blockID);
  145. uint[] signals;
  146. if (input) {
  147. signals = new uint[bps.inputCount];
  148. for (uint i = 0u; i < bps.inputCount; i++)
  149. {
  150. signals[i] = bps.firstInputID + i;
  151. }
  152. } else {
  153. signals = new uint[bps.outputCount];
  154. for (uint i = 0u; i < bps.outputCount; i++)
  155. {
  156. signals[i] = bps.firstOutputID + i;
  157. }
  158. }
  159. return signals;
  160. }
  161. public EGID[] GetSignalInputs(EGID blockID)
  162. {
  163. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(blockID);
  164. EGID[] inputs = new EGID[ports.inputCount];
  165. for (uint i = 0; i < ports.inputCount; i++)
  166. {
  167. inputs[i] = new EGID(i + ports.firstInputID, NamedExclusiveGroup<InputPortsGroup>.Group);
  168. }
  169. return inputs;
  170. }
  171. public EGID[] GetSignalOutputs(EGID blockID)
  172. {
  173. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(blockID);
  174. EGID[] outputs = new EGID[ports.outputCount];
  175. for (uint i = 0; i < ports.outputCount; i++)
  176. {
  177. outputs[i] = new EGID(i + ports.firstOutputID, NamedExclusiveGroup<OutputPortsGroup>.Group);
  178. }
  179. return outputs;
  180. }
  181. public EGID MatchBlockInputToPort(Block block, byte portUsage, out bool exists)
  182. {
  183. BlockPortsStruct ports = GetFromDbOrInitData<BlockPortsStruct>(block, block.Id, out exists);
  184. return new EGID(ports.firstInputID + portUsage, NamedExclusiveGroup<InputPortsGroup>.Group);
  185. }
  186. public EGID MatchBlockInputToPort(EGID block, byte portUsage, out bool exists)
  187. {
  188. if (!entitiesDB.Exists<BlockPortsStruct>(block))
  189. {
  190. exists = false;
  191. return default;
  192. }
  193. exists = true;
  194. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(block);
  195. return new EGID(ports.firstInputID + portUsage, NamedExclusiveGroup<InputPortsGroup>.Group);
  196. }
  197. public EGID MatchBlockOutputToPort(Block block, byte portUsage, out bool exists)
  198. {
  199. BlockPortsStruct ports = GetFromDbOrInitData<BlockPortsStruct>(block, block.Id, out exists);
  200. return new EGID(ports.firstOutputID + portUsage, NamedExclusiveGroup<OutputPortsGroup>.Group);
  201. }
  202. public EGID MatchBlockOutputToPort(EGID block, byte portUsage, out bool exists)
  203. {
  204. if (!entitiesDB.Exists<BlockPortsStruct>(block))
  205. {
  206. exists = false;
  207. return default;
  208. }
  209. exists = true;
  210. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(block);
  211. return new EGID(ports.firstOutputID + portUsage, NamedExclusiveGroup<OutputPortsGroup>.Group);
  212. }
  213. public ref WireEntityStruct MatchPortToWire(EGID portID, EGID blockID, out bool exists)
  214. {
  215. ref PortEntityStruct port = ref entitiesDB.QueryEntity<PortEntityStruct>(portID);
  216. var wires = entitiesDB.QueryEntities<WireEntityStruct>(NamedExclusiveGroup<WiresGroup>.Group);
  217. var wiresB = wires.ToBuffer().buffer;
  218. for (uint i = 0; i < wires.count; i++)
  219. {
  220. if ((wiresB[i].destinationPortUsage == port.usage && wiresB[i].destinationBlockEGID == blockID)
  221. || (wiresB[i].sourcePortUsage == port.usage && wiresB[i].sourceBlockEGID == blockID))
  222. {
  223. exists = true;
  224. return ref wiresB[i];
  225. }
  226. }
  227. exists = false;
  228. WireEntityStruct[] defRef = new WireEntityStruct[1];
  229. return ref defRef[0];
  230. }
  231. public ref WireEntityStruct MatchBlocksToWire(EGID startBlock, EGID endBlock, out bool exists, byte startPort = byte.MaxValue,
  232. byte endPort = byte.MaxValue)
  233. {
  234. EGID[] startPorts;
  235. if (startPort == byte.MaxValue)
  236. {
  237. // search all output ports on source block
  238. startPorts = GetSignalOutputs(startBlock);
  239. }
  240. else
  241. {
  242. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(startBlock);
  243. startPorts = new EGID[] {new EGID(ports.firstOutputID + startPort, NamedExclusiveGroup<OutputPortsGroup>.Group) };
  244. }
  245. EGID[] endPorts;
  246. if (startPort == byte.MaxValue)
  247. {
  248. // search all input ports on destination block
  249. endPorts = GetSignalInputs(endBlock);
  250. }
  251. else
  252. {
  253. BlockPortsStruct ports = entitiesDB.QueryEntity<BlockPortsStruct>(endBlock);
  254. endPorts = new EGID[] {new EGID(ports.firstInputID + endPort, NamedExclusiveGroup<InputPortsGroup>.Group) };
  255. }
  256. EntityCollection<WireEntityStruct> wires = entitiesDB.QueryEntities<WireEntityStruct>(NamedExclusiveGroup<WiresGroup>.Group);
  257. var wiresB = wires.ToBuffer().buffer;
  258. for (int endIndex = 0; endIndex < endPorts.Length; endIndex++)
  259. {
  260. PortEntityStruct endPES = entitiesDB.QueryEntity<PortEntityStruct>(endPorts[endIndex]);
  261. for (int startIndex = 0; startIndex < startPorts.Length; startIndex++)
  262. {
  263. PortEntityStruct startPES = entitiesDB.QueryEntity<PortEntityStruct>(startPorts[startIndex]);
  264. for (int w = 0; w < wires.count; w++)
  265. {
  266. if ((wiresB[w].destinationPortUsage == endPES.usage && wiresB[w].destinationBlockEGID == endBlock)
  267. && (wiresB[w].sourcePortUsage == startPES.usage && wiresB[w].sourceBlockEGID == startBlock))
  268. {
  269. exists = true;
  270. return ref wiresB[w];
  271. }
  272. }
  273. }
  274. }
  275. exists = false;
  276. WireEntityStruct[] defRef = new WireEntityStruct[1];
  277. return ref defRef[0];
  278. }
  279. public ref ChannelDataStruct GetChannelDataStruct(EGID portID, out bool exists)
  280. {
  281. ref PortEntityStruct port = ref entitiesDB.QueryEntity<PortEntityStruct>(portID);
  282. var channels = entitiesDB.QueryEntities<ChannelDataStruct>(NamedExclusiveGroup<ChannelDataGroup>.Group);
  283. var channelsB = channels.ToBuffer();
  284. if (port.firstChannelIndexCachedInSim < channels.count)
  285. {
  286. exists = true;
  287. return ref channelsB.buffer[port.firstChannelIndexCachedInSim];
  288. }
  289. exists = false;
  290. ChannelDataStruct[] defRef = new ChannelDataStruct[1];
  291. return ref defRef[0];
  292. }
  293. public EGID[] GetElectricBlocks()
  294. {
  295. var res = new FasterList<EGID>();
  296. foreach (var (coll, _) in entitiesDB.QueryEntities<BlockPortsStruct>())
  297. {
  298. var collB = coll.ToBuffer();
  299. for (int i = 0; i < coll.count; i++)
  300. {
  301. ref BlockPortsStruct s = ref collB.buffer[i];
  302. res.Add(s.ID);
  303. }
  304. }
  305. return res.ToArray();
  306. }
  307. public EGID[] WiredToInput(EGID block, byte port)
  308. {
  309. WireEntityStruct[] wireEntityStructs = Search(NamedExclusiveGroup<WiresGroup>.Group,
  310. (WireEntityStruct wes) => wes.destinationPortUsage == port && wes.destinationBlockEGID == block);
  311. EGID[] result = new EGID[wireEntityStructs.Length];
  312. for (uint i = 0; i < wireEntityStructs.Length; i++)
  313. {
  314. result[i] = wireEntityStructs[i].ID;
  315. }
  316. return result;
  317. }
  318. public EGID[] WiredToOutput(EGID block, byte port)
  319. {
  320. WireEntityStruct[] wireEntityStructs = Search(NamedExclusiveGroup<WiresGroup>.Group,
  321. (WireEntityStruct wes) => wes.sourcePortUsage == port && wes.sourceBlockEGID == block);
  322. EGID[] result = new EGID[wireEntityStructs.Length];
  323. for (uint i = 0; i < wireEntityStructs.Length; i++)
  324. {
  325. result[i] = wireEntityStructs[i].ID;
  326. }
  327. return result;
  328. }
  329. private T[] Search<T>(ExclusiveGroup group, Func<T, bool> isMatch) where T : unmanaged, IEntityComponent
  330. {
  331. FasterList<T> results = new FasterList<T>();
  332. EntityCollection<T> components = entitiesDB.QueryEntities<T>(group);
  333. var componentsB = components.ToBuffer();
  334. for (uint i = 0; i < components.count; i++)
  335. {
  336. if (isMatch(componentsB.buffer[i]))
  337. {
  338. results.Add(componentsB.buffer[i]);
  339. }
  340. }
  341. return results.ToArray();
  342. }
  343. private ref T GetFromDbOrInitData<T>(Block block, EGID id, out bool exists) where T : unmanaged, IEntityComponent
  344. {
  345. T[] defRef = new T[1];
  346. if (entitiesDB.Exists<T>(id))
  347. {
  348. exists = true;
  349. return ref entitiesDB.QueryEntity<T>(id);
  350. }
  351. if (block == null || block.InitData.Group == null)
  352. {
  353. exists = false;
  354. return ref defRef[0];
  355. }
  356. EntityInitializer initializer = new EntityInitializer(block.Id, block.InitData.Group, block.InitData.Reference);
  357. if (initializer.Has<T>())
  358. {
  359. exists = true;
  360. return ref initializer.Get<T>();
  361. }
  362. exists = false;
  363. return ref defRef[0];
  364. }
  365. private EntityCollection<ChannelDataStruct> GetSignalStruct(uint signalID, out uint index, bool input = true)
  366. {
  367. ExclusiveGroup group = input
  368. ? NamedExclusiveGroup<InputPortsGroup>.Group
  369. : NamedExclusiveGroup<OutputPortsGroup>.Group;
  370. if (entitiesDB.Exists<PortEntityStruct>(signalID, group))
  371. {
  372. index = entitiesDB.QueryEntity<PortEntityStruct>(signalID, group).anyChannelIndex;
  373. var channelData =
  374. entitiesDB.QueryEntities<ChannelDataStruct>(NamedExclusiveGroup<ChannelDataGroup>.Group);
  375. return channelData;
  376. }
  377. index = 0;
  378. return default; //count: 0
  379. }
  380. }
  381. }