ecsy.module.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  1. /**
  2. * Return the name of a component
  3. * @param {Component} Component
  4. * @private
  5. */
  6. /**
  7. * Get a key from a list of components
  8. * @param {Array(Component)} Components Array of components to generate the key
  9. * @private
  10. */
  11. function queryKey(Components) {
  12. var ids = [];
  13. for (var n = 0; n < Components.length; n++) {
  14. var T = Components[n];
  15. if (!componentRegistered(T)) {
  16. throw new Error(`Tried to create a query with an unregistered component`);
  17. }
  18. if (typeof T === "object") {
  19. var operator = T.operator === "not" ? "!" : T.operator;
  20. ids.push(operator + T.Component._typeId);
  21. } else {
  22. ids.push(T._typeId);
  23. }
  24. }
  25. return ids.sort().join("-");
  26. }
  27. // Detector for browser's "window"
  28. const hasWindow = typeof window !== "undefined";
  29. // performance.now() "polyfill"
  30. const now =
  31. hasWindow && typeof window.performance !== "undefined"
  32. ? performance.now.bind(performance)
  33. : Date.now.bind(Date);
  34. function componentRegistered(T) {
  35. return (
  36. (typeof T === "object" && T.Component._typeId !== undefined) ||
  37. (T.isComponent && T._typeId !== undefined)
  38. );
  39. }
  40. class SystemManager {
  41. constructor(world) {
  42. this._systems = [];
  43. this._executeSystems = []; // Systems that have `execute` method
  44. this.world = world;
  45. this.lastExecutedSystem = null;
  46. }
  47. registerSystem(SystemClass, attributes) {
  48. if (!SystemClass.isSystem) {
  49. throw new Error(
  50. `System '${SystemClass.name}' does not extend 'System' class`
  51. );
  52. }
  53. if (this.getSystem(SystemClass) !== undefined) {
  54. console.warn(`System '${SystemClass.getName()}' already registered.`);
  55. return this;
  56. }
  57. var system = new SystemClass(this.world, attributes);
  58. if (system.init) system.init(attributes);
  59. system.order = this._systems.length;
  60. this._systems.push(system);
  61. if (system.execute) {
  62. this._executeSystems.push(system);
  63. this.sortSystems();
  64. }
  65. return this;
  66. }
  67. unregisterSystem(SystemClass) {
  68. let system = this.getSystem(SystemClass);
  69. if (system === undefined) {
  70. console.warn(
  71. `Can unregister system '${SystemClass.getName()}'. It doesn't exist.`
  72. );
  73. return this;
  74. }
  75. this._systems.splice(this._systems.indexOf(system), 1);
  76. if (system.execute) {
  77. this._executeSystems.splice(this._executeSystems.indexOf(system), 1);
  78. }
  79. // @todo Add system.unregister() call to free resources
  80. return this;
  81. }
  82. sortSystems() {
  83. this._executeSystems.sort((a, b) => {
  84. return a.priority - b.priority || a.order - b.order;
  85. });
  86. }
  87. getSystem(SystemClass) {
  88. return this._systems.find((s) => s instanceof SystemClass);
  89. }
  90. getSystems() {
  91. return this._systems;
  92. }
  93. removeSystem(SystemClass) {
  94. var index = this._systems.indexOf(SystemClass);
  95. if (!~index) return;
  96. this._systems.splice(index, 1);
  97. }
  98. executeSystem(system, delta, time) {
  99. if (system.initialized) {
  100. if (system.canExecute()) {
  101. let startTime = now();
  102. system.execute(delta, time);
  103. system.executeTime = now() - startTime;
  104. this.lastExecutedSystem = system;
  105. system.clearEvents();
  106. }
  107. }
  108. }
  109. stop() {
  110. this._executeSystems.forEach((system) => system.stop());
  111. }
  112. execute(delta, time, forcePlay) {
  113. this._executeSystems.forEach(
  114. (system) =>
  115. (forcePlay || system.enabled) && this.executeSystem(system, delta, time)
  116. );
  117. }
  118. stats() {
  119. var stats = {
  120. numSystems: this._systems.length,
  121. systems: {},
  122. };
  123. for (var i = 0; i < this._systems.length; i++) {
  124. var system = this._systems[i];
  125. var systemStats = (stats.systems[system.getName()] = {
  126. queries: {},
  127. executeTime: system.executeTime,
  128. });
  129. for (var name in system.ctx) {
  130. systemStats.queries[name] = system.ctx[name].stats();
  131. }
  132. }
  133. return stats;
  134. }
  135. }
  136. class ObjectPool {
  137. // @todo Add initial size
  138. constructor(T, initialSize) {
  139. this.freeList = [];
  140. this.count = 0;
  141. this.T = T;
  142. this.isObjectPool = true;
  143. if (typeof initialSize !== "undefined") {
  144. this.expand(initialSize);
  145. }
  146. }
  147. acquire() {
  148. // Grow the list by 20%ish if we're out
  149. if (this.freeList.length <= 0) {
  150. this.expand(Math.round(this.count * 0.2) + 1);
  151. }
  152. var item = this.freeList.pop();
  153. return item;
  154. }
  155. release(item) {
  156. item.reset();
  157. this.freeList.push(item);
  158. }
  159. expand(count) {
  160. for (var n = 0; n < count; n++) {
  161. var clone = new this.T();
  162. clone._pool = this;
  163. this.freeList.push(clone);
  164. }
  165. this.count += count;
  166. }
  167. totalSize() {
  168. return this.count;
  169. }
  170. totalFree() {
  171. return this.freeList.length;
  172. }
  173. totalUsed() {
  174. return this.count - this.freeList.length;
  175. }
  176. }
  177. /**
  178. * @private
  179. * @class EventDispatcher
  180. */
  181. class EventDispatcher {
  182. constructor() {
  183. this._listeners = {};
  184. this.stats = {
  185. fired: 0,
  186. handled: 0,
  187. };
  188. }
  189. /**
  190. * Add an event listener
  191. * @param {String} eventName Name of the event to listen
  192. * @param {Function} listener Callback to trigger when the event is fired
  193. */
  194. addEventListener(eventName, listener) {
  195. let listeners = this._listeners;
  196. if (listeners[eventName] === undefined) {
  197. listeners[eventName] = [];
  198. }
  199. if (listeners[eventName].indexOf(listener) === -1) {
  200. listeners[eventName].push(listener);
  201. }
  202. }
  203. /**
  204. * Check if an event listener is already added to the list of listeners
  205. * @param {String} eventName Name of the event to check
  206. * @param {Function} listener Callback for the specified event
  207. */
  208. hasEventListener(eventName, listener) {
  209. return (
  210. this._listeners[eventName] !== undefined &&
  211. this._listeners[eventName].indexOf(listener) !== -1
  212. );
  213. }
  214. /**
  215. * Remove an event listener
  216. * @param {String} eventName Name of the event to remove
  217. * @param {Function} listener Callback for the specified event
  218. */
  219. removeEventListener(eventName, listener) {
  220. var listenerArray = this._listeners[eventName];
  221. if (listenerArray !== undefined) {
  222. var index = listenerArray.indexOf(listener);
  223. if (index !== -1) {
  224. listenerArray.splice(index, 1);
  225. }
  226. }
  227. }
  228. /**
  229. * Dispatch an event
  230. * @param {String} eventName Name of the event to dispatch
  231. * @param {Entity} entity (Optional) Entity to emit
  232. * @param {Component} component
  233. */
  234. dispatchEvent(eventName, entity, component) {
  235. this.stats.fired++;
  236. var listenerArray = this._listeners[eventName];
  237. if (listenerArray !== undefined) {
  238. var array = listenerArray.slice(0);
  239. for (var i = 0; i < array.length; i++) {
  240. array[i].call(this, entity, component);
  241. }
  242. }
  243. }
  244. /**
  245. * Reset stats counters
  246. */
  247. resetCounters() {
  248. this.stats.fired = this.stats.handled = 0;
  249. }
  250. }
  251. class Query {
  252. /**
  253. * @param {Array(Component)} Components List of types of components to query
  254. */
  255. constructor(Components, manager) {
  256. this.Components = [];
  257. this.NotComponents = [];
  258. Components.forEach((component) => {
  259. if (typeof component === "object") {
  260. this.NotComponents.push(component.Component);
  261. } else {
  262. this.Components.push(component);
  263. }
  264. });
  265. if (this.Components.length === 0) {
  266. throw new Error("Can't create a query without components");
  267. }
  268. this.entities = [];
  269. this.eventDispatcher = new EventDispatcher();
  270. // This query is being used by a reactive system
  271. this.reactive = false;
  272. this.key = queryKey(Components);
  273. // Fill the query with the existing entities
  274. for (var i = 0; i < manager._entities.length; i++) {
  275. var entity = manager._entities[i];
  276. if (this.match(entity)) {
  277. // @todo ??? this.addEntity(entity); => preventing the event to be generated
  278. entity.queries.push(this);
  279. this.entities.push(entity);
  280. }
  281. }
  282. }
  283. /**
  284. * Add entity to this query
  285. * @param {Entity} entity
  286. */
  287. addEntity(entity) {
  288. entity.queries.push(this);
  289. this.entities.push(entity);
  290. this.eventDispatcher.dispatchEvent(Query.prototype.ENTITY_ADDED, entity);
  291. }
  292. /**
  293. * Remove entity from this query
  294. * @param {Entity} entity
  295. */
  296. removeEntity(entity) {
  297. let index = this.entities.indexOf(entity);
  298. if (~index) {
  299. this.entities.splice(index, 1);
  300. index = entity.queries.indexOf(this);
  301. entity.queries.splice(index, 1);
  302. this.eventDispatcher.dispatchEvent(
  303. Query.prototype.ENTITY_REMOVED,
  304. entity
  305. );
  306. }
  307. }
  308. match(entity) {
  309. return (
  310. entity.hasAllComponents(this.Components) &&
  311. !entity.hasAnyComponents(this.NotComponents)
  312. );
  313. }
  314. toJSON() {
  315. return {
  316. key: this.key,
  317. reactive: this.reactive,
  318. components: {
  319. included: this.Components.map((C) => C.name),
  320. not: this.NotComponents.map((C) => C.name),
  321. },
  322. numEntities: this.entities.length,
  323. };
  324. }
  325. /**
  326. * Return stats for this query
  327. */
  328. stats() {
  329. return {
  330. numComponents: this.Components.length,
  331. numEntities: this.entities.length,
  332. };
  333. }
  334. }
  335. Query.prototype.ENTITY_ADDED = "Query#ENTITY_ADDED";
  336. Query.prototype.ENTITY_REMOVED = "Query#ENTITY_REMOVED";
  337. Query.prototype.COMPONENT_CHANGED = "Query#COMPONENT_CHANGED";
  338. /**
  339. * @private
  340. * @class QueryManager
  341. */
  342. class QueryManager {
  343. constructor(world) {
  344. this._world = world;
  345. // Queries indexed by a unique identifier for the components it has
  346. this._queries = {};
  347. }
  348. onEntityRemoved(entity) {
  349. for (var queryName in this._queries) {
  350. var query = this._queries[queryName];
  351. if (entity.queries.indexOf(query) !== -1) {
  352. query.removeEntity(entity);
  353. }
  354. }
  355. }
  356. /**
  357. * Callback when a component is added to an entity
  358. * @param {Entity} entity Entity that just got the new component
  359. * @param {Component} Component Component added to the entity
  360. */
  361. onEntityComponentAdded(entity, Component) {
  362. // @todo Use bitmask for checking components?
  363. // Check each indexed query to see if we need to add this entity to the list
  364. for (var queryName in this._queries) {
  365. var query = this._queries[queryName];
  366. if (
  367. !!~query.NotComponents.indexOf(Component) &&
  368. ~query.entities.indexOf(entity)
  369. ) {
  370. query.removeEntity(entity);
  371. continue;
  372. }
  373. // Add the entity only if:
  374. // Component is in the query
  375. // and Entity has ALL the components of the query
  376. // and Entity is not already in the query
  377. if (
  378. !~query.Components.indexOf(Component) ||
  379. !query.match(entity) ||
  380. ~query.entities.indexOf(entity)
  381. )
  382. continue;
  383. query.addEntity(entity);
  384. }
  385. }
  386. /**
  387. * Callback when a component is removed from an entity
  388. * @param {Entity} entity Entity to remove the component from
  389. * @param {Component} Component Component to remove from the entity
  390. */
  391. onEntityComponentRemoved(entity, Component) {
  392. for (var queryName in this._queries) {
  393. var query = this._queries[queryName];
  394. if (
  395. !!~query.NotComponents.indexOf(Component) &&
  396. !~query.entities.indexOf(entity) &&
  397. query.match(entity)
  398. ) {
  399. query.addEntity(entity);
  400. continue;
  401. }
  402. if (
  403. !!~query.Components.indexOf(Component) &&
  404. !!~query.entities.indexOf(entity) &&
  405. !query.match(entity)
  406. ) {
  407. query.removeEntity(entity);
  408. continue;
  409. }
  410. }
  411. }
  412. /**
  413. * Get a query for the specified components
  414. * @param {Component} Components Components that the query should have
  415. */
  416. getQuery(Components) {
  417. var key = queryKey(Components);
  418. var query = this._queries[key];
  419. if (!query) {
  420. this._queries[key] = query = new Query(Components, this._world);
  421. }
  422. return query;
  423. }
  424. /**
  425. * Return some stats from this class
  426. */
  427. stats() {
  428. var stats = {};
  429. for (var queryName in this._queries) {
  430. stats[queryName] = this._queries[queryName].stats();
  431. }
  432. return stats;
  433. }
  434. }
  435. class Component {
  436. constructor(props) {
  437. if (props !== false) {
  438. const schema = this.constructor.schema;
  439. for (const key in schema) {
  440. if (props && props.hasOwnProperty(key)) {
  441. this[key] = props[key];
  442. } else {
  443. const schemaProp = schema[key];
  444. if (schemaProp.hasOwnProperty("default")) {
  445. this[key] = schemaProp.type.clone(schemaProp.default);
  446. } else {
  447. const type = schemaProp.type;
  448. this[key] = type.clone(type.default);
  449. }
  450. }
  451. }
  452. if ( props !== undefined) {
  453. this.checkUndefinedAttributes(props);
  454. }
  455. }
  456. this._pool = null;
  457. }
  458. copy(source) {
  459. const schema = this.constructor.schema;
  460. for (const key in schema) {
  461. const prop = schema[key];
  462. if (source.hasOwnProperty(key)) {
  463. this[key] = prop.type.copy(source[key], this[key]);
  464. }
  465. }
  466. // @DEBUG
  467. {
  468. this.checkUndefinedAttributes(source);
  469. }
  470. return this;
  471. }
  472. clone() {
  473. return new this.constructor().copy(this);
  474. }
  475. reset() {
  476. const schema = this.constructor.schema;
  477. for (const key in schema) {
  478. const schemaProp = schema[key];
  479. if (schemaProp.hasOwnProperty("default")) {
  480. this[key] = schemaProp.type.copy(schemaProp.default, this[key]);
  481. } else {
  482. const type = schemaProp.type;
  483. this[key] = type.copy(type.default, this[key]);
  484. }
  485. }
  486. }
  487. dispose() {
  488. if (this._pool) {
  489. this._pool.release(this);
  490. }
  491. }
  492. getName() {
  493. return this.constructor.getName();
  494. }
  495. checkUndefinedAttributes(src) {
  496. const schema = this.constructor.schema;
  497. // Check that the attributes defined in source are also defined in the schema
  498. Object.keys(src).forEach((srcKey) => {
  499. if (!schema.hasOwnProperty(srcKey)) {
  500. console.warn(
  501. `Trying to set attribute '${srcKey}' not defined in the '${this.constructor.name}' schema. Please fix the schema, the attribute value won't be set`
  502. );
  503. }
  504. });
  505. }
  506. }
  507. Component.schema = {};
  508. Component.isComponent = true;
  509. Component.getName = function () {
  510. return this.displayName || this.name;
  511. };
  512. class SystemStateComponent extends Component {}
  513. SystemStateComponent.isSystemStateComponent = true;
  514. class EntityPool extends ObjectPool {
  515. constructor(entityManager, entityClass, initialSize) {
  516. super(entityClass, undefined);
  517. this.entityManager = entityManager;
  518. if (typeof initialSize !== "undefined") {
  519. this.expand(initialSize);
  520. }
  521. }
  522. expand(count) {
  523. for (var n = 0; n < count; n++) {
  524. var clone = new this.T(this.entityManager);
  525. clone._pool = this;
  526. this.freeList.push(clone);
  527. }
  528. this.count += count;
  529. }
  530. }
  531. /**
  532. * @private
  533. * @class EntityManager
  534. */
  535. class EntityManager {
  536. constructor(world) {
  537. this.world = world;
  538. this.componentsManager = world.componentsManager;
  539. // All the entities in this instance
  540. this._entities = [];
  541. this._nextEntityId = 0;
  542. this._entitiesByNames = {};
  543. this._queryManager = new QueryManager(this);
  544. this.eventDispatcher = new EventDispatcher();
  545. this._entityPool = new EntityPool(
  546. this,
  547. this.world.options.entityClass,
  548. this.world.options.entityPoolSize
  549. );
  550. // Deferred deletion
  551. this.entitiesWithComponentsToRemove = [];
  552. this.entitiesToRemove = [];
  553. this.deferredRemovalEnabled = true;
  554. }
  555. getEntityByName(name) {
  556. return this._entitiesByNames[name];
  557. }
  558. /**
  559. * Create a new entity
  560. */
  561. createEntity(name) {
  562. var entity = this._entityPool.acquire();
  563. entity.alive = true;
  564. entity.name = name || "";
  565. if (name) {
  566. if (this._entitiesByNames[name]) {
  567. console.warn(`Entity name '${name}' already exist`);
  568. } else {
  569. this._entitiesByNames[name] = entity;
  570. }
  571. }
  572. this._entities.push(entity);
  573. this.eventDispatcher.dispatchEvent(ENTITY_CREATED, entity);
  574. return entity;
  575. }
  576. // COMPONENTS
  577. /**
  578. * Add a component to an entity
  579. * @param {Entity} entity Entity where the component will be added
  580. * @param {Component} Component Component to be added to the entity
  581. * @param {Object} values Optional values to replace the default attributes
  582. */
  583. entityAddComponent(entity, Component, values) {
  584. // @todo Probably define Component._typeId with a default value and avoid using typeof
  585. if (
  586. typeof Component._typeId === "undefined" &&
  587. !this.world.componentsManager._ComponentsMap[Component._typeId]
  588. ) {
  589. throw new Error(
  590. `Attempted to add unregistered component "${Component.getName()}"`
  591. );
  592. }
  593. if (~entity._ComponentTypes.indexOf(Component)) {
  594. {
  595. console.warn(
  596. "Component type already exists on entity.",
  597. entity,
  598. Component.getName()
  599. );
  600. }
  601. return;
  602. }
  603. entity._ComponentTypes.push(Component);
  604. if (Component.__proto__ === SystemStateComponent) {
  605. entity.numStateComponents++;
  606. }
  607. var componentPool = this.world.componentsManager.getComponentsPool(
  608. Component
  609. );
  610. var component = componentPool
  611. ? componentPool.acquire()
  612. : new Component(values);
  613. if (componentPool && values) {
  614. component.copy(values);
  615. }
  616. entity._components[Component._typeId] = component;
  617. this._queryManager.onEntityComponentAdded(entity, Component);
  618. this.world.componentsManager.componentAddedToEntity(Component);
  619. this.eventDispatcher.dispatchEvent(COMPONENT_ADDED, entity, Component);
  620. }
  621. /**
  622. * Remove a component from an entity
  623. * @param {Entity} entity Entity which will get removed the component
  624. * @param {*} Component Component to remove from the entity
  625. * @param {Bool} immediately If you want to remove the component immediately instead of deferred (Default is false)
  626. */
  627. entityRemoveComponent(entity, Component, immediately) {
  628. var index = entity._ComponentTypes.indexOf(Component);
  629. if (!~index) return;
  630. this.eventDispatcher.dispatchEvent(COMPONENT_REMOVE, entity, Component);
  631. if (immediately) {
  632. this._entityRemoveComponentSync(entity, Component, index);
  633. } else {
  634. if (entity._ComponentTypesToRemove.length === 0)
  635. this.entitiesWithComponentsToRemove.push(entity);
  636. entity._ComponentTypes.splice(index, 1);
  637. entity._ComponentTypesToRemove.push(Component);
  638. entity._componentsToRemove[Component._typeId] =
  639. entity._components[Component._typeId];
  640. delete entity._components[Component._typeId];
  641. }
  642. // Check each indexed query to see if we need to remove it
  643. this._queryManager.onEntityComponentRemoved(entity, Component);
  644. if (Component.__proto__ === SystemStateComponent) {
  645. entity.numStateComponents--;
  646. // Check if the entity was a ghost waiting for the last system state component to be removed
  647. if (entity.numStateComponents === 0 && !entity.alive) {
  648. entity.remove();
  649. }
  650. }
  651. }
  652. _entityRemoveComponentSync(entity, Component, index) {
  653. // Remove T listing on entity and property ref, then free the component.
  654. entity._ComponentTypes.splice(index, 1);
  655. var component = entity._components[Component._typeId];
  656. delete entity._components[Component._typeId];
  657. component.dispose();
  658. this.world.componentsManager.componentRemovedFromEntity(Component);
  659. }
  660. /**
  661. * Remove all the components from an entity
  662. * @param {Entity} entity Entity from which the components will be removed
  663. */
  664. entityRemoveAllComponents(entity, immediately) {
  665. let Components = entity._ComponentTypes;
  666. for (let j = Components.length - 1; j >= 0; j--) {
  667. if (Components[j].__proto__ !== SystemStateComponent)
  668. this.entityRemoveComponent(entity, Components[j], immediately);
  669. }
  670. }
  671. /**
  672. * Remove the entity from this manager. It will clear also its components
  673. * @param {Entity} entity Entity to remove from the manager
  674. * @param {Bool} immediately If you want to remove the component immediately instead of deferred (Default is false)
  675. */
  676. removeEntity(entity, immediately) {
  677. var index = this._entities.indexOf(entity);
  678. if (!~index) throw new Error("Tried to remove entity not in list");
  679. entity.alive = false;
  680. this.entityRemoveAllComponents(entity, immediately);
  681. if (entity.numStateComponents === 0) {
  682. // Remove from entity list
  683. this.eventDispatcher.dispatchEvent(ENTITY_REMOVED, entity);
  684. this._queryManager.onEntityRemoved(entity);
  685. if (immediately === true) {
  686. this._releaseEntity(entity, index);
  687. } else {
  688. this.entitiesToRemove.push(entity);
  689. }
  690. }
  691. }
  692. _releaseEntity(entity, index) {
  693. this._entities.splice(index, 1);
  694. if (this._entitiesByNames[entity.name]) {
  695. delete this._entitiesByNames[entity.name];
  696. }
  697. entity._pool.release(entity);
  698. }
  699. /**
  700. * Remove all entities from this manager
  701. */
  702. removeAllEntities() {
  703. for (var i = this._entities.length - 1; i >= 0; i--) {
  704. this.removeEntity(this._entities[i]);
  705. }
  706. }
  707. processDeferredRemoval() {
  708. if (!this.deferredRemovalEnabled) {
  709. return;
  710. }
  711. for (let i = 0; i < this.entitiesToRemove.length; i++) {
  712. let entity = this.entitiesToRemove[i];
  713. let index = this._entities.indexOf(entity);
  714. this._releaseEntity(entity, index);
  715. }
  716. this.entitiesToRemove.length = 0;
  717. for (let i = 0; i < this.entitiesWithComponentsToRemove.length; i++) {
  718. let entity = this.entitiesWithComponentsToRemove[i];
  719. while (entity._ComponentTypesToRemove.length > 0) {
  720. let Component = entity._ComponentTypesToRemove.pop();
  721. var component = entity._componentsToRemove[Component._typeId];
  722. delete entity._componentsToRemove[Component._typeId];
  723. component.dispose();
  724. this.world.componentsManager.componentRemovedFromEntity(Component);
  725. //this._entityRemoveComponentSync(entity, Component, index);
  726. }
  727. }
  728. this.entitiesWithComponentsToRemove.length = 0;
  729. }
  730. /**
  731. * Get a query based on a list of components
  732. * @param {Array(Component)} Components List of components that will form the query
  733. */
  734. queryComponents(Components) {
  735. return this._queryManager.getQuery(Components);
  736. }
  737. // EXTRAS
  738. /**
  739. * Return number of entities
  740. */
  741. count() {
  742. return this._entities.length;
  743. }
  744. /**
  745. * Return some stats
  746. */
  747. stats() {
  748. var stats = {
  749. numEntities: this._entities.length,
  750. numQueries: Object.keys(this._queryManager._queries).length,
  751. queries: this._queryManager.stats(),
  752. numComponentPool: Object.keys(this.componentsManager._componentPool)
  753. .length,
  754. componentPool: {},
  755. eventDispatcher: this.eventDispatcher.stats,
  756. };
  757. for (var ecsyComponentId in this.componentsManager._componentPool) {
  758. var pool = this.componentsManager._componentPool[ecsyComponentId];
  759. stats.componentPool[pool.T.getName()] = {
  760. used: pool.totalUsed(),
  761. size: pool.count,
  762. };
  763. }
  764. return stats;
  765. }
  766. }
  767. const ENTITY_CREATED = "EntityManager#ENTITY_CREATE";
  768. const ENTITY_REMOVED = "EntityManager#ENTITY_REMOVED";
  769. const COMPONENT_ADDED = "EntityManager#COMPONENT_ADDED";
  770. const COMPONENT_REMOVE = "EntityManager#COMPONENT_REMOVE";
  771. class ComponentManager {
  772. constructor() {
  773. this.Components = [];
  774. this._ComponentsMap = {};
  775. this._componentPool = {};
  776. this.numComponents = {};
  777. this.nextComponentId = 0;
  778. }
  779. hasComponent(Component) {
  780. return this.Components.indexOf(Component) !== -1;
  781. }
  782. registerComponent(Component, objectPool) {
  783. if (this.Components.indexOf(Component) !== -1) {
  784. console.warn(
  785. `Component type: '${Component.getName()}' already registered.`
  786. );
  787. return;
  788. }
  789. const schema = Component.schema;
  790. if (!schema) {
  791. throw new Error(
  792. `Component "${Component.getName()}" has no schema property.`
  793. );
  794. }
  795. for (const propName in schema) {
  796. const prop = schema[propName];
  797. if (!prop.type) {
  798. throw new Error(
  799. `Invalid schema for component "${Component.getName()}". Missing type for "${propName}" property.`
  800. );
  801. }
  802. }
  803. Component._typeId = this.nextComponentId++;
  804. this.Components.push(Component);
  805. this._ComponentsMap[Component._typeId] = Component;
  806. this.numComponents[Component._typeId] = 0;
  807. if (objectPool === undefined) {
  808. objectPool = new ObjectPool(Component);
  809. } else if (objectPool === false) {
  810. objectPool = undefined;
  811. }
  812. this._componentPool[Component._typeId] = objectPool;
  813. }
  814. componentAddedToEntity(Component) {
  815. this.numComponents[Component._typeId]++;
  816. }
  817. componentRemovedFromEntity(Component) {
  818. this.numComponents[Component._typeId]--;
  819. }
  820. getComponentsPool(Component) {
  821. return this._componentPool[Component._typeId];
  822. }
  823. }
  824. const Version = "0.3.1";
  825. const proxyMap = new WeakMap();
  826. const proxyHandler = {
  827. set(target, prop) {
  828. throw new Error(
  829. `Tried to write to "${target.constructor.getName()}#${String(
  830. prop
  831. )}" on immutable component. Use .getMutableComponent() to modify a component.`
  832. );
  833. },
  834. };
  835. function wrapImmutableComponent(T, component) {
  836. if (component === undefined) {
  837. return undefined;
  838. }
  839. let wrappedComponent = proxyMap.get(component);
  840. if (!wrappedComponent) {
  841. wrappedComponent = new Proxy(component, proxyHandler);
  842. proxyMap.set(component, wrappedComponent);
  843. }
  844. return wrappedComponent;
  845. }
  846. class Entity {
  847. constructor(entityManager) {
  848. this._entityManager = entityManager || null;
  849. // Unique ID for this entity
  850. this.id = entityManager._nextEntityId++;
  851. // List of components types the entity has
  852. this._ComponentTypes = [];
  853. // Instance of the components
  854. this._components = {};
  855. this._componentsToRemove = {};
  856. // Queries where the entity is added
  857. this.queries = [];
  858. // Used for deferred removal
  859. this._ComponentTypesToRemove = [];
  860. this.alive = false;
  861. //if there are state components on a entity, it can't be removed completely
  862. this.numStateComponents = 0;
  863. }
  864. // COMPONENTS
  865. getComponent(Component, includeRemoved) {
  866. var component = this._components[Component._typeId];
  867. if (!component && includeRemoved === true) {
  868. component = this._componentsToRemove[Component._typeId];
  869. }
  870. return wrapImmutableComponent(Component, component)
  871. ;
  872. }
  873. getRemovedComponent(Component) {
  874. const component = this._componentsToRemove[Component._typeId];
  875. return wrapImmutableComponent(Component, component)
  876. ;
  877. }
  878. getComponents() {
  879. return this._components;
  880. }
  881. getComponentsToRemove() {
  882. return this._componentsToRemove;
  883. }
  884. getComponentTypes() {
  885. return this._ComponentTypes;
  886. }
  887. getMutableComponent(Component) {
  888. var component = this._components[Component._typeId];
  889. if (!component) {
  890. return;
  891. }
  892. for (var i = 0; i < this.queries.length; i++) {
  893. var query = this.queries[i];
  894. // @todo accelerate this check. Maybe having query._Components as an object
  895. // @todo add Not components
  896. if (query.reactive && query.Components.indexOf(Component) !== -1) {
  897. query.eventDispatcher.dispatchEvent(
  898. Query.prototype.COMPONENT_CHANGED,
  899. this,
  900. component
  901. );
  902. }
  903. }
  904. return component;
  905. }
  906. addComponent(Component, values) {
  907. this._entityManager.entityAddComponent(this, Component, values);
  908. return this;
  909. }
  910. removeComponent(Component, forceImmediate) {
  911. this._entityManager.entityRemoveComponent(this, Component, forceImmediate);
  912. return this;
  913. }
  914. hasComponent(Component, includeRemoved) {
  915. return (
  916. !!~this._ComponentTypes.indexOf(Component) ||
  917. (includeRemoved === true && this.hasRemovedComponent(Component))
  918. );
  919. }
  920. hasRemovedComponent(Component) {
  921. return !!~this._ComponentTypesToRemove.indexOf(Component);
  922. }
  923. hasAllComponents(Components) {
  924. for (var i = 0; i < Components.length; i++) {
  925. if (!this.hasComponent(Components[i])) return false;
  926. }
  927. return true;
  928. }
  929. hasAnyComponents(Components) {
  930. for (var i = 0; i < Components.length; i++) {
  931. if (this.hasComponent(Components[i])) return true;
  932. }
  933. return false;
  934. }
  935. removeAllComponents(forceImmediate) {
  936. return this._entityManager.entityRemoveAllComponents(this, forceImmediate);
  937. }
  938. copy(src) {
  939. // TODO: This can definitely be optimized
  940. for (var ecsyComponentId in src._components) {
  941. var srcComponent = src._components[ecsyComponentId];
  942. this.addComponent(srcComponent.constructor);
  943. var component = this.getComponent(srcComponent.constructor);
  944. component.copy(srcComponent);
  945. }
  946. return this;
  947. }
  948. clone() {
  949. return new Entity(this._entityManager).copy(this);
  950. }
  951. reset() {
  952. this.id = this._entityManager._nextEntityId++;
  953. this._ComponentTypes.length = 0;
  954. this.queries.length = 0;
  955. for (var ecsyComponentId in this._components) {
  956. delete this._components[ecsyComponentId];
  957. }
  958. }
  959. remove(forceImmediate) {
  960. return this._entityManager.removeEntity(this, forceImmediate);
  961. }
  962. }
  963. const DEFAULT_OPTIONS = {
  964. entityPoolSize: 0,
  965. entityClass: Entity,
  966. };
  967. class World {
  968. constructor(options = {}) {
  969. this.options = Object.assign({}, DEFAULT_OPTIONS, options);
  970. this.componentsManager = new ComponentManager(this);
  971. this.entityManager = new EntityManager(this);
  972. this.systemManager = new SystemManager(this);
  973. this.enabled = true;
  974. this.eventQueues = {};
  975. if (hasWindow && typeof CustomEvent !== "undefined") {
  976. var event = new CustomEvent("ecsy-world-created", {
  977. detail: { world: this, version: Version },
  978. });
  979. window.dispatchEvent(event);
  980. }
  981. this.lastTime = now() / 1000;
  982. }
  983. registerComponent(Component, objectPool) {
  984. this.componentsManager.registerComponent(Component, objectPool);
  985. return this;
  986. }
  987. registerSystem(System, attributes) {
  988. this.systemManager.registerSystem(System, attributes);
  989. return this;
  990. }
  991. hasRegisteredComponent(Component) {
  992. return this.componentsManager.hasComponent(Component);
  993. }
  994. unregisterSystem(System) {
  995. this.systemManager.unregisterSystem(System);
  996. return this;
  997. }
  998. getSystem(SystemClass) {
  999. return this.systemManager.getSystem(SystemClass);
  1000. }
  1001. getSystems() {
  1002. return this.systemManager.getSystems();
  1003. }
  1004. execute(delta, time) {
  1005. if (!delta) {
  1006. time = now() / 1000;
  1007. delta = time - this.lastTime;
  1008. this.lastTime = time;
  1009. }
  1010. if (this.enabled) {
  1011. this.systemManager.execute(delta, time);
  1012. this.entityManager.processDeferredRemoval();
  1013. }
  1014. }
  1015. stop() {
  1016. this.enabled = false;
  1017. }
  1018. play() {
  1019. this.enabled = true;
  1020. }
  1021. createEntity(name) {
  1022. return this.entityManager.createEntity(name);
  1023. }
  1024. stats() {
  1025. var stats = {
  1026. entities: this.entityManager.stats(),
  1027. system: this.systemManager.stats(),
  1028. };
  1029. return stats;
  1030. }
  1031. }
  1032. class System {
  1033. canExecute() {
  1034. if (this._mandatoryQueries.length === 0) return true;
  1035. for (let i = 0; i < this._mandatoryQueries.length; i++) {
  1036. var query = this._mandatoryQueries[i];
  1037. if (query.entities.length === 0) {
  1038. return false;
  1039. }
  1040. }
  1041. return true;
  1042. }
  1043. getName() {
  1044. return this.constructor.getName();
  1045. }
  1046. constructor(world, attributes) {
  1047. this.world = world;
  1048. this.enabled = true;
  1049. // @todo Better naming :)
  1050. this._queries = {};
  1051. this.queries = {};
  1052. this.priority = 0;
  1053. // Used for stats
  1054. this.executeTime = 0;
  1055. if (attributes && attributes.priority) {
  1056. this.priority = attributes.priority;
  1057. }
  1058. this._mandatoryQueries = [];
  1059. this.initialized = true;
  1060. if (this.constructor.queries) {
  1061. for (var queryName in this.constructor.queries) {
  1062. var queryConfig = this.constructor.queries[queryName];
  1063. var Components = queryConfig.components;
  1064. if (!Components || Components.length === 0) {
  1065. throw new Error("'components' attribute can't be empty in a query");
  1066. }
  1067. // Detect if the components have already been registered
  1068. let unregisteredComponents = Components.filter(
  1069. (Component) => !componentRegistered(Component)
  1070. );
  1071. if (unregisteredComponents.length > 0) {
  1072. throw new Error(
  1073. `Tried to create a query '${
  1074. this.constructor.name
  1075. }.${queryName}' with unregistered components: [${unregisteredComponents
  1076. .map((c) => c.getName())
  1077. .join(", ")}]`
  1078. );
  1079. }
  1080. var query = this.world.entityManager.queryComponents(Components);
  1081. this._queries[queryName] = query;
  1082. if (queryConfig.mandatory === true) {
  1083. this._mandatoryQueries.push(query);
  1084. }
  1085. this.queries[queryName] = {
  1086. results: query.entities,
  1087. };
  1088. // Reactive configuration added/removed/changed
  1089. var validEvents = ["added", "removed", "changed"];
  1090. const eventMapping = {
  1091. added: Query.prototype.ENTITY_ADDED,
  1092. removed: Query.prototype.ENTITY_REMOVED,
  1093. changed: Query.prototype.COMPONENT_CHANGED, // Query.prototype.ENTITY_CHANGED
  1094. };
  1095. if (queryConfig.listen) {
  1096. validEvents.forEach((eventName) => {
  1097. if (!this.execute) {
  1098. console.warn(
  1099. `System '${this.getName()}' has defined listen events (${validEvents.join(
  1100. ", "
  1101. )}) for query '${queryName}' but it does not implement the 'execute' method.`
  1102. );
  1103. }
  1104. // Is the event enabled on this system's query?
  1105. if (queryConfig.listen[eventName]) {
  1106. let event = queryConfig.listen[eventName];
  1107. if (eventName === "changed") {
  1108. query.reactive = true;
  1109. if (event === true) {
  1110. // Any change on the entity from the components in the query
  1111. let eventList = (this.queries[queryName][eventName] = []);
  1112. query.eventDispatcher.addEventListener(
  1113. Query.prototype.COMPONENT_CHANGED,
  1114. (entity) => {
  1115. // Avoid duplicates
  1116. if (eventList.indexOf(entity) === -1) {
  1117. eventList.push(entity);
  1118. }
  1119. }
  1120. );
  1121. } else if (Array.isArray(event)) {
  1122. let eventList = (this.queries[queryName][eventName] = []);
  1123. query.eventDispatcher.addEventListener(
  1124. Query.prototype.COMPONENT_CHANGED,
  1125. (entity, changedComponent) => {
  1126. // Avoid duplicates
  1127. if (
  1128. event.indexOf(changedComponent.constructor) !== -1 &&
  1129. eventList.indexOf(entity) === -1
  1130. ) {
  1131. eventList.push(entity);
  1132. }
  1133. }
  1134. );
  1135. }
  1136. } else {
  1137. let eventList = (this.queries[queryName][eventName] = []);
  1138. query.eventDispatcher.addEventListener(
  1139. eventMapping[eventName],
  1140. (entity) => {
  1141. // @fixme overhead?
  1142. if (eventList.indexOf(entity) === -1)
  1143. eventList.push(entity);
  1144. }
  1145. );
  1146. }
  1147. }
  1148. });
  1149. }
  1150. }
  1151. }
  1152. }
  1153. stop() {
  1154. this.executeTime = 0;
  1155. this.enabled = false;
  1156. }
  1157. play() {
  1158. this.enabled = true;
  1159. }
  1160. // @question rename to clear queues?
  1161. clearEvents() {
  1162. for (let queryName in this.queries) {
  1163. var query = this.queries[queryName];
  1164. if (query.added) {
  1165. query.added.length = 0;
  1166. }
  1167. if (query.removed) {
  1168. query.removed.length = 0;
  1169. }
  1170. if (query.changed) {
  1171. if (Array.isArray(query.changed)) {
  1172. query.changed.length = 0;
  1173. } else {
  1174. for (let name in query.changed) {
  1175. query.changed[name].length = 0;
  1176. }
  1177. }
  1178. }
  1179. }
  1180. }
  1181. toJSON() {
  1182. var json = {
  1183. name: this.getName(),
  1184. enabled: this.enabled,
  1185. executeTime: this.executeTime,
  1186. priority: this.priority,
  1187. queries: {},
  1188. };
  1189. if (this.constructor.queries) {
  1190. var queries = this.constructor.queries;
  1191. for (let queryName in queries) {
  1192. let query = this.queries[queryName];
  1193. let queryDefinition = queries[queryName];
  1194. let jsonQuery = (json.queries[queryName] = {
  1195. key: this._queries[queryName].key,
  1196. });
  1197. jsonQuery.mandatory = queryDefinition.mandatory === true;
  1198. jsonQuery.reactive =
  1199. queryDefinition.listen &&
  1200. (queryDefinition.listen.added === true ||
  1201. queryDefinition.listen.removed === true ||
  1202. queryDefinition.listen.changed === true ||
  1203. Array.isArray(queryDefinition.listen.changed));
  1204. if (jsonQuery.reactive) {
  1205. jsonQuery.listen = {};
  1206. const methods = ["added", "removed", "changed"];
  1207. methods.forEach((method) => {
  1208. if (query[method]) {
  1209. jsonQuery.listen[method] = {
  1210. entities: query[method].length,
  1211. };
  1212. }
  1213. });
  1214. }
  1215. }
  1216. }
  1217. return json;
  1218. }
  1219. }
  1220. System.isSystem = true;
  1221. System.getName = function () {
  1222. return this.displayName || this.name;
  1223. };
  1224. function Not(Component) {
  1225. return {
  1226. operator: "not",
  1227. Component: Component,
  1228. };
  1229. }
  1230. class TagComponent extends Component {
  1231. constructor() {
  1232. super(false);
  1233. }
  1234. }
  1235. TagComponent.isTagComponent = true;
  1236. const copyValue = (src) => src;
  1237. const cloneValue = (src) => src;
  1238. const copyArray = (src, dest) => {
  1239. if (!src) {
  1240. return src;
  1241. }
  1242. if (!dest) {
  1243. return src.slice();
  1244. }
  1245. dest.length = 0;
  1246. for (let i = 0; i < src.length; i++) {
  1247. dest.push(src[i]);
  1248. }
  1249. return dest;
  1250. };
  1251. const cloneArray = (src) => src && src.slice();
  1252. const copyJSON = (src) => JSON.parse(JSON.stringify(src));
  1253. const cloneJSON = (src) => JSON.parse(JSON.stringify(src));
  1254. const copyCopyable = (src, dest) => {
  1255. if (!src) {
  1256. return src;
  1257. }
  1258. if (!dest) {
  1259. return src.clone();
  1260. }
  1261. return dest.copy(src);
  1262. };
  1263. const cloneClonable = (src) => src && src.clone();
  1264. function createType(typeDefinition) {
  1265. var mandatoryProperties = ["name", "default", "copy", "clone"];
  1266. var undefinedProperties = mandatoryProperties.filter((p) => {
  1267. return !typeDefinition.hasOwnProperty(p);
  1268. });
  1269. if (undefinedProperties.length > 0) {
  1270. throw new Error(
  1271. `createType expects a type definition with the following properties: ${undefinedProperties.join(
  1272. ", "
  1273. )}`
  1274. );
  1275. }
  1276. typeDefinition.isType = true;
  1277. return typeDefinition;
  1278. }
  1279. /**
  1280. * Standard types
  1281. */
  1282. const Types = {
  1283. Number: createType({
  1284. name: "Number",
  1285. default: 0,
  1286. copy: copyValue,
  1287. clone: cloneValue,
  1288. }),
  1289. Boolean: createType({
  1290. name: "Boolean",
  1291. default: false,
  1292. copy: copyValue,
  1293. clone: cloneValue,
  1294. }),
  1295. String: createType({
  1296. name: "String",
  1297. default: "",
  1298. copy: copyValue,
  1299. clone: cloneValue,
  1300. }),
  1301. Array: createType({
  1302. name: "Array",
  1303. default: [],
  1304. copy: copyArray,
  1305. clone: cloneArray,
  1306. }),
  1307. Ref: createType({
  1308. name: "Ref",
  1309. default: undefined,
  1310. copy: copyValue,
  1311. clone: cloneValue,
  1312. }),
  1313. JSON: createType({
  1314. name: "JSON",
  1315. default: null,
  1316. copy: copyJSON,
  1317. clone: cloneJSON,
  1318. }),
  1319. };
  1320. function generateId(length) {
  1321. var result = "";
  1322. var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  1323. var charactersLength = characters.length;
  1324. for (var i = 0; i < length; i++) {
  1325. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  1326. }
  1327. return result;
  1328. }
  1329. function injectScript(src, onLoad) {
  1330. var script = document.createElement("script");
  1331. // @todo Use link to the ecsy-devtools repo?
  1332. script.src = src;
  1333. script.onload = onLoad;
  1334. (document.head || document.documentElement).appendChild(script);
  1335. }
  1336. /* global Peer */
  1337. function hookConsoleAndErrors(connection) {
  1338. var wrapFunctions = ["error", "warning", "log"];
  1339. wrapFunctions.forEach((key) => {
  1340. if (typeof console[key] === "function") {
  1341. var fn = console[key].bind(console);
  1342. console[key] = (...args) => {
  1343. connection.send({
  1344. method: "console",
  1345. type: key,
  1346. args: JSON.stringify(args),
  1347. });
  1348. return fn.apply(null, args);
  1349. };
  1350. }
  1351. });
  1352. window.addEventListener("error", (error) => {
  1353. connection.send({
  1354. method: "error",
  1355. error: JSON.stringify({
  1356. message: error.error.message,
  1357. stack: error.error.stack,
  1358. }),
  1359. });
  1360. });
  1361. }
  1362. function includeRemoteIdHTML(remoteId) {
  1363. let infoDiv = document.createElement("div");
  1364. infoDiv.style.cssText = `
  1365. align-items: center;
  1366. background-color: #333;
  1367. color: #aaa;
  1368. display:flex;
  1369. font-family: Arial;
  1370. font-size: 1.1em;
  1371. height: 40px;
  1372. justify-content: center;
  1373. left: 0;
  1374. opacity: 0.9;
  1375. position: absolute;
  1376. right: 0;
  1377. text-align: center;
  1378. top: 0;
  1379. `;
  1380. infoDiv.innerHTML = `Open ECSY devtools to connect to this page using the code:&nbsp;<b style="color: #fff">${remoteId}</b>&nbsp;<button onClick="generateNewCode()">Generate new code</button>`;
  1381. document.body.appendChild(infoDiv);
  1382. return infoDiv;
  1383. }
  1384. function enableRemoteDevtools(remoteId) {
  1385. if (!hasWindow) {
  1386. console.warn("Remote devtools not available outside the browser");
  1387. return;
  1388. }
  1389. window.generateNewCode = () => {
  1390. window.localStorage.clear();
  1391. remoteId = generateId(6);
  1392. window.localStorage.setItem("ecsyRemoteId", remoteId);
  1393. window.location.reload(false);
  1394. };
  1395. remoteId = remoteId || window.localStorage.getItem("ecsyRemoteId");
  1396. if (!remoteId) {
  1397. remoteId = generateId(6);
  1398. window.localStorage.setItem("ecsyRemoteId", remoteId);
  1399. }
  1400. let infoDiv = includeRemoteIdHTML(remoteId);
  1401. window.__ECSY_REMOTE_DEVTOOLS_INJECTED = true;
  1402. window.__ECSY_REMOTE_DEVTOOLS = {};
  1403. let Version = "";
  1404. // This is used to collect the worlds created before the communication is being established
  1405. let worldsBeforeLoading = [];
  1406. let onWorldCreated = (e) => {
  1407. var world = e.detail.world;
  1408. Version = e.detail.version;
  1409. worldsBeforeLoading.push(world);
  1410. };
  1411. window.addEventListener("ecsy-world-created", onWorldCreated);
  1412. let onLoaded = () => {
  1413. // var peer = new Peer(remoteId);
  1414. var peer = new Peer(remoteId, {
  1415. host: "peerjs.ecsy.io",
  1416. secure: true,
  1417. port: 443,
  1418. config: {
  1419. iceServers: [
  1420. { url: "stun:stun.l.google.com:19302" },
  1421. { url: "stun:stun1.l.google.com:19302" },
  1422. { url: "stun:stun2.l.google.com:19302" },
  1423. { url: "stun:stun3.l.google.com:19302" },
  1424. { url: "stun:stun4.l.google.com:19302" },
  1425. ],
  1426. },
  1427. debug: 3,
  1428. });
  1429. peer.on("open", (/* id */) => {
  1430. peer.on("connection", (connection) => {
  1431. window.__ECSY_REMOTE_DEVTOOLS.connection = connection;
  1432. connection.on("open", function () {
  1433. // infoDiv.style.visibility = "hidden";
  1434. infoDiv.innerHTML = "Connected";
  1435. // Receive messages
  1436. connection.on("data", function (data) {
  1437. if (data.type === "init") {
  1438. var script = document.createElement("script");
  1439. script.setAttribute("type", "text/javascript");
  1440. script.onload = () => {
  1441. script.parentNode.removeChild(script);
  1442. // Once the script is injected we don't need to listen
  1443. window.removeEventListener(
  1444. "ecsy-world-created",
  1445. onWorldCreated
  1446. );
  1447. worldsBeforeLoading.forEach((world) => {
  1448. var event = new CustomEvent("ecsy-world-created", {
  1449. detail: { world: world, version: Version },
  1450. });
  1451. window.dispatchEvent(event);
  1452. });
  1453. };
  1454. script.innerHTML = data.script;
  1455. (document.head || document.documentElement).appendChild(script);
  1456. script.onload();
  1457. hookConsoleAndErrors(connection);
  1458. } else if (data.type === "executeScript") {
  1459. let value = eval(data.script);
  1460. if (data.returnEval) {
  1461. connection.send({
  1462. method: "evalReturn",
  1463. value: value,
  1464. });
  1465. }
  1466. }
  1467. });
  1468. });
  1469. });
  1470. });
  1471. };
  1472. // Inject PeerJS script
  1473. injectScript(
  1474. "https://cdn.jsdelivr.net/npm/peerjs@0.3.20/dist/peer.min.js",
  1475. onLoaded
  1476. );
  1477. }
  1478. if (hasWindow) {
  1479. const urlParams = new URLSearchParams(window.location.search);
  1480. // @todo Provide a way to disable it if needed
  1481. if (urlParams.has("enable-remote-devtools")) {
  1482. enableRemoteDevtools();
  1483. }
  1484. }
  1485. export { Component, Not, ObjectPool, System, SystemStateComponent, TagComponent, Types, Version, World, Entity as _Entity, cloneArray, cloneClonable, cloneJSON, cloneValue, copyArray, copyCopyable, copyJSON, copyValue, createType, enableRemoteDevtools };