ConcernementMapItem.vue 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121
  1. <script>
  2. import { nextTick } from 'vue'
  3. import Matter from "matter-js";
  4. import MatterAttractors from "matter-attractors";
  5. // Matter.use(MatterAttractors);
  6. // import polydecomp from "poly-decomp";
  7. import paper from 'paper';
  8. // import { easeInOutQuad, easeInOutQuart } from 'easing-utils';
  9. import Tween from "@tweenjs/tween.js";
  10. import { mapState, mapActions } from 'pinia'
  11. import { ConcernementsStore } from '@/stores/concernements'
  12. import { CommonStore } from '@/stores/common'
  13. import { mdiPictureInPictureBottomRight } from '@mdi/js';
  14. export default {
  15. inject: ['canvasMap', 'matterEngine'],
  16. data() {
  17. return {
  18. id: null,
  19. cid: null,
  20. concernement: null,
  21. active_revision: null,
  22. entities: null,
  23. superposedEntitesIDsList: [],
  24. canvas: null,
  25. ctx: null,
  26. pos : {
  27. x: 0,
  28. y: 0
  29. },
  30. ray: 100,
  31. time: 0,
  32. salientPoints: [],
  33. scale: 1,
  34. prev_scale: 1,
  35. opacity: 0,
  36. tween: null,
  37. is_open: false,
  38. is_opening: false,
  39. is_closing: false,
  40. is_hover: false,
  41. //
  42. body: null,
  43. body_parts: [],
  44. constraint: null,
  45. //
  46. paper_main_object: {},
  47. paper_groups: {}
  48. }
  49. },
  50. props: ['mapitem'],
  51. computed: {
  52. ...mapState(ConcernementsStore,['map_mode',
  53. 'concernementsByID',
  54. 'allSuperpositions_byid',
  55. 'allMapItems_byid',
  56. 'opened_concernement',
  57. 'opened_entite_id']),
  58. ...mapState(CommonStore,['hover_elmt',
  59. 'map_item_ray',
  60. 'cartouch_width',
  61. 'cartouch_is_opened',
  62. 'paper_symbol_definitions'])
  63. },
  64. created () {
  65. // console.log('ConcernementMapItem created', this.mapitem);
  66. // this.id = this.superposition_id ? `${this.cid}___${this.superposition_id}` : this.cid;
  67. this.id = this.mapitem.id;
  68. this.concernement = this.mapitem.concernement;
  69. this.cid = this.concernement.id;
  70. // console.log('mapitem this.cid', this.cid);
  71. this.active_revision = this.concernement.active_revision;
  72. // console.log(`ConcernementsMapItem ${this.id} created`);
  73. // this.entites = this.concernement.entites
  74. this.entites = this.concernement.revisions_byid[this.concernement.revision_id].entites;
  75. // disable concernement if less than 3 entite
  76. if(this.entites.length < 3){
  77. this.hideShowConcernement(this.concernement.id, false);
  78. } else{
  79. // record canvas and ctx for rendering (drawing)
  80. this.canvas = this.canvasMap.canvas
  81. this.ctx = this.canvasMap.ctx
  82. // define the ray regarding the width and height of screen
  83. this.ray = this.map_item_ray;
  84. // console.log(`this.ray: ${this.ray}`);
  85. //
  86. this.parseEntityPointsValues()
  87. // this.getSalientPoints()
  88. this.getJarvisEnvelopeConvexe()
  89. // define init position of the item
  90. this.pos = this.getRandomPos();
  91. //
  92. this.getSuperposedEntitesIDsList();
  93. //
  94. this.initMatterBody()
  95. //
  96. this.initPaperObjects()
  97. }
  98. // this.setConcernementMapItem(this.cid, this);
  99. },
  100. // mounted() {
  101. // console.log(`ConcernementsMapItem ${this.concernement.id} mounted`, this.canvasMap.canvas);
  102. // },
  103. // beforeUnmount () {
  104. unmounted () {
  105. // console.log(`mapitem ${this.id} unmounted`);
  106. if(this.mapitem.clone) {
  107. // console.log(`this.paper_main_object ${this.paper_main_object.id}`, this.paper_main_object);
  108. paper.project.getItem({id:this.paper_main_object.id}).remove();
  109. };
  110. if (this.body) {
  111. Matter.Composite.remove(this.matterEngine.world, this.body);
  112. }
  113. },
  114. watch: {
  115. // canvasMap (n, o) {
  116. // console.log("concernementItem watch canvasMap", o, n);
  117. // }
  118. canvasMap: {
  119. handler (n, o){
  120. // console.log("concernementItem watch canvasMap.ctx", typeof this.canvas, o, n);
  121. if (!this.canvas) {
  122. this.initCanvasMap()
  123. }
  124. },
  125. deep: true
  126. },
  127. opened_concernement: {
  128. handler (n, o) {
  129. if (!n) { // if there is no opened concernement
  130. this.is_open = false;
  131. this.applyShuffleForces();
  132. } else {
  133. if(this.cid === n.id && this.id === n.opened_mapitem_id){
  134. this.is_open = true;
  135. }else{
  136. this.is_open = false;
  137. }
  138. }
  139. },
  140. deep: true
  141. },
  142. is_open: {
  143. handler (n, o) {
  144. // console.log('mapItem watch is_open', n, this.is_open);
  145. if(n){ // opened
  146. this.openClose(true);
  147. }else if(o) { // closed if was opened
  148. this.openClose(false);
  149. }
  150. },
  151. deep: true
  152. },
  153. map_mode: {
  154. handler (n, o) {
  155. console.log('concernementMapItem watch map_mode', o, n);
  156. if (n === 'terraindevie' && !this.opened_concernement) {
  157. this.applyShuffleForces(); // apply a little force to check the map when returning to terrain de vie
  158. }
  159. if (this.is_open & n !== o) {
  160. this.setPaperContents();
  161. }
  162. if (n !== o) {
  163. this.handlePaperVisibilityOnMapMode()
  164. }
  165. },
  166. deep: true
  167. },
  168. hover_elmt: {
  169. handler (n, o) {
  170. // console.log(`watch hover_elmt ${this.id}`, o, n);
  171. if (n && (n.type === 'concernement' || n.type === 'superposition') && n.id === this.id) {
  172. this.is_hover = true;
  173. } else {
  174. this.is_hover = false;
  175. }
  176. },
  177. deep: true
  178. },
  179. is_hover: {
  180. handler (n, o) {
  181. this.onIsHover(n);
  182. },
  183. deep: true
  184. },
  185. concernement: {
  186. handler (n, o){
  187. // check for active_revision changes
  188. // do not trigger on first variable filling (if o is null)
  189. if(this.is_open && o && o.active_revision && n.active_revision && this.map_mode === "terraindevie"){
  190. // be aware that here o & n active_revision are already the same :( !?
  191. console.log(`concernementMapItem watch concernement o.active_revision:${o.active_revision}, n.active_revision:${n.active_revision}`);
  192. this.resetPaperActiveRevision();
  193. }
  194. },
  195. deep: true
  196. }
  197. },
  198. methods: {
  199. ...mapActions(CommonStore,['setHoverElmt']),
  200. ...mapActions(ConcernementsStore,['openCloseConcernements',
  201. // 'setConcernementMapItem',
  202. 'hideShowConcernement',
  203. 'setBesoinPaperId',
  204. 'setOpenedDoleanceField',
  205. 'setOpenedRecit']),
  206. // getResponsiveRay(){
  207. // return Math.min(this.canvas.width, this.canvas.height) * 0.08;
  208. // },
  209. parseEntityPointsValues (){
  210. // converts data (menace/maintien, actuel/future, prise) into atcual position x,y
  211. for (let r = 0; r < this.concernement.revisions.length; r++) { // loop through all revisions
  212. for (let i = 0; i < this.concernement.revisions[r].entites.length; i++) { // loop through all entite for each revision
  213. let entite = this.concernement.revisions[r].entites[i]
  214. // console.log('entite', entite);
  215. entite.display = {
  216. alpha: null,
  217. ray: null
  218. }
  219. // RAYON
  220. // https://stackoverflow.com/questions/5731863/mapping-a-numeric-range-onto-another
  221. // slope = (output_end - output_start) / (input_end - input_start)
  222. // output = output_start + slope * (input - input_start)
  223. // from range 0 -> 100 to range 0 -> this.ray
  224. let init_max = 100
  225. let slope = this.ray / init_max
  226. entite.display.ray = slope * (init_max - entite.prise);
  227. // if (this.concernement.id === 28) {
  228. // console.log(`entity prise: ${entite.prise} | ray: ${entite.display.ray}`);
  229. // }
  230. // ANGLE
  231. // -90 <= mm <= 90
  232. if (entite.actuelfuture) {
  233. // future en haut : 180 <= a <= 360
  234. // from -90 -> 90 to range 180 -> 360
  235. entite.display.alpha = entite.menacemaintien + 270
  236. } else {
  237. // actuel: en bas : O <= a <= 180
  238. // from -90 -> 90 to range 180 -> 0
  239. entite.display.alpha = -1 * entite.menacemaintien + 90
  240. }
  241. // POSITION X Y (par rapport au centre du concernement)
  242. entite.display.pos = {
  243. x: entite.display.ray * Math.cos(entite.display.alpha * (Math.PI/180)),
  244. y: entite.display.ray * Math.sin(entite.display.alpha * (Math.PI/180))
  245. }
  246. // if (entite.entite) {
  247. // this.entites_byid[entite.entite.id].display = entite.display;
  248. // }
  249. }
  250. }
  251. },
  252. getSalientPoints_OLD() {
  253. // debugger
  254. // console.log(this.entites);
  255. let arc = 360/30;
  256. // loop through arcs
  257. // for (let i = 360/arc; i >= 0 ; i--) {
  258. for (let i = 0; i <= 360/arc ; i++) {
  259. // loop through entities to find the farest on the arc
  260. let max_r = 0;
  261. let farest = null;
  262. for (let j = 0; j < this.entites.length; j++) {
  263. let entite = this.entites[j];
  264. if(arc*i <= entite.display.alpha && entite.display.alpha <= arc*i+arc) { // if entity is in arc
  265. if (entite.display.ray > max_r) { // && entite.display.ray > this.ray/2 // and farest from minimu
  266. // if entity is farest from precedent one
  267. max_r = entite.display.ray;
  268. // recalcul x & y to get a little padding between entite and contour by increasing ray
  269. farest = {
  270. alpha: entite.display.alpha,
  271. ray: entite.display.ray,
  272. pos: {
  273. x: (entite.display.ray + 3) * Math.cos(entite.display.alpha * (Math.PI/180)),
  274. y: (entite.display.ray + 3) * Math.sin(entite.display.alpha * (Math.PI/180))
  275. }
  276. };
  277. }
  278. }
  279. }
  280. if (farest) {
  281. this.salientPoints.push(farest)
  282. }
  283. }
  284. // console.log(`this.salientPoints ${this.concernement.id}`, this.salientPoints);
  285. },
  286. getJarvisEnvelopeConvexe(){
  287. this.salientPoints = [];
  288. let entites = this.concernement.revisions_byid[this.concernement.active_revision].entites;
  289. // console.log(`getJarvisEnvelopeConvexe ${this.id}`, this.entites.length);
  290. // https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/
  291. // find the most left point
  292. let l, min_x = null;
  293. for (let i = 0; i < entites.length; i++) {
  294. let entite = entites[i];
  295. let x = entite.display.ray * Math.cos(entite.display.alpha * (Math.PI/180));
  296. if(!min_x || min_x > x){
  297. l = i;
  298. min_x = x;
  299. }
  300. }
  301. // Start from leftmost point, keep moving clockwise
  302. // until reach the start point again. This loop runs O(h)
  303. // times where h is number of points in result or output.
  304. let p = l, q;
  305. do {
  306. // console.log(`do while ${this.id}`, p);
  307. // Add current point to result
  308. let entite = entites[p];
  309. let farest = {
  310. alpha: entite.display.alpha,
  311. ray: entite.display.ray,
  312. pos: {
  313. x: (entite.display.ray) * Math.cos(entite.display.alpha * (Math.PI/180)),
  314. y: (entite.display.ray) * Math.sin(entite.display.alpha * (Math.PI/180))
  315. }
  316. };
  317. this.salientPoints.push(farest);
  318. // Search for a point 'q' such that
  319. // orientation(p, q, x) is clockwise
  320. // for all points 'x'. The idea is to keep
  321. // track of last visited most clockwise
  322. // point in q. If any point 'i' is more
  323. // clockwise than q, then update q.
  324. q = (p + 1) % entites.length;
  325. for (let i = 0; i < entites.length; i++) {
  326. let p_x = (entites[p].display.ray) * Math.cos(entites[p].display.alpha * (Math.PI/180));
  327. let p_y = (entites[p].display.ray) * Math.sin(entites[p].display.alpha * (Math.PI/180));
  328. let i_x = (entites[i].display.ray) * Math.cos(entites[i].display.alpha * (Math.PI/180));
  329. let i_y = (entites[i].display.ray) * Math.sin(entites[i].display.alpha * (Math.PI/180));
  330. let q_x = (entites[q].display.ray) * Math.cos(entites[q].display.alpha * (Math.PI/180));
  331. let q_y = (entites[q].display.ray) * Math.sin(entites[q].display.alpha * (Math.PI/180));
  332. let val = (i_y - p_y) * (q_x - i_x) - (i_x - p_x) * (q_y - i_y);
  333. // If i is more clockwise than current q, then update q
  334. if (val > 0){
  335. q = i;
  336. }
  337. }
  338. // Now q is the most clockwise with
  339. // respect to p. Set p as q for next iteration,
  340. // so that q is added to result 'hull'
  341. p = q;
  342. } while (p != l);
  343. },
  344. getRandomPos(){
  345. let pad = 200;
  346. // if (this.concernement.id === 56) {
  347. // return {
  348. // x: Math.random() > 0.5 ? pad : this.canvas.width - pad,
  349. // y: pad + this.ray/2 + Math.random()*(this.canvas.height - this.ray - pad)
  350. // };
  351. // } else {
  352. return {
  353. x: pad + this.getGaussianRandom()*(this.canvas.width - pad*2),
  354. y: pad + this.getGaussianRandom()*(this.canvas.height - pad*2)
  355. };
  356. // }
  357. },
  358. getGaussianRandom(){
  359. // INFO https://stackoverflow.com/a/49434653
  360. let u = 0, v = 0;
  361. while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
  362. while(v === 0) v = Math.random();
  363. let num = Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
  364. num = num / 10.0 + 0.5; // Translate to 0 -> 1
  365. if (num > 1 || num < 0) return this.getGaussianRandom() // resample between 0 and 1
  366. return num
  367. },
  368. getSuperposedEntitesIDsList(){
  369. if (this.concernement.superpositions) {
  370. // loop through all concernement superpositions couples of this concernement
  371. for(let [couple_id, superpositions] of Object.entries(this.concernement.superpositions)){
  372. // loop through all superpositions of each couple
  373. for(let [superposition_id, superposition] of Object.entries(superpositions)){
  374. if (this.mapitem.superposition_ids.indexOf(superposition_id) >= 0) {
  375. switch (this.cid) { // get the right eid regarding the cid
  376. case superposition[0].cid:
  377. this.superposedEntitesIDsList.push(superposition[0].eid);
  378. break;
  379. case superposition[1].cid:
  380. this.superposedEntitesIDsList.push(superposition[1].eid);
  381. break;
  382. }
  383. }
  384. }
  385. }
  386. }
  387. // console.log('superposedEntitesIDsList', this.superposedEntitesIDsList);
  388. },
  389. // MATTER BODY
  390. initMatterBody (){
  391. // MATTER
  392. // create the matter body and add it to the engine
  393. if (!this.body) {
  394. // console.log('concernementItem creating body');
  395. // INFO https://github.com/liabru/matter-attractors/issues/8
  396. // INFO https://github.com/liabru/matter-attractors/blob/master/index.js
  397. // INFO https://github.com/liabru/matter-attractors/blob/master/build/matter-attractors.js#L180
  398. MatterAttractors.Attractors.gravityConstant = -20;
  399. // Create parts of the body : main big circle & entities
  400. // INFO map a range of numbers to another range of numbers https://stackoverflow.com/a/46462321
  401. let entite_range = [3, 100];
  402. let ray_range = [this.ray*0.8,this.ray*1.2];
  403. let ray = ray_range[0] + (this.entites.length - entite_range[0]) * (ray_range[1] - ray_range[0]) / (entite_range[1] - entite_range[0]);
  404. this.body_parts = [
  405. Matter.Bodies.circle(0, 0, ray, {
  406. // item_type: 'concernement',
  407. // id: this.concernement.id,
  408. })
  409. ];
  410. // INFO map a range of numbers to another range of numbers https://stackoverflow.com/a/46462321
  411. let mass_range = [5,15];
  412. let mass = mass_range[0] + (this.entites.length - entite_range[0]) * (mass_range[1] - mass_range[0]) / (entite_range[1] - entite_range[0]);
  413. // create the body
  414. this.body = Matter.Body.create({
  415. parts: this.body_parts,
  416. item_type: 'concernement',
  417. id: this.id,
  418. frictionAir: 0,
  419. // mass: Math.pow(3, this.entites.length),
  420. // mass: 10,
  421. mass: mass,
  422. restitution: 0.06,
  423. collisionFilter: {
  424. group: -1
  425. },
  426. plugin: {
  427. attractors: [
  428. // // there is a built in helper function for Newtonian gravity!
  429. // // you can find out how it works in index.js
  430. MatterAttractors.Attractors.gravity
  431. // function(bodyA, bodyB) {
  432. // var force = {
  433. // x: (bodyA.position.x - bodyB.position.x) * 1e-6,
  434. // y: (bodyA.position.y - bodyB.position.y) * 1e-6
  435. // }
  436. // // apply force to both bodies
  437. // Matter.Body.applyForce(bodyA, bodyA.position, force);
  438. // Matter.Body.applyForce(bodyB, bodyB.position, Matter.Vector.neg(force));
  439. // }
  440. // INFO https://github.com/liabru/matter-attractors/blob/master/build/matter-attractors.js#L192
  441. // function (bodyA, bodyB){
  442. // // use Newton's law of gravitation
  443. // var bToA = Matter.Vector.sub(bodyB.position, bodyA.position),
  444. // distanceSq = Matter.Vector.magnitudeSquared(bToA) || 0.0001,
  445. // normal = Matter.Vector.normalise(bToA),
  446. // magnitude = -MatterAttractors.Attractors.gravityConstant * (bodyA.mass * bodyB.mass / distanceSq),
  447. // force = Matter.Vector.mult(normal, magnitude);
  448. // // to apply forces to both bodies
  449. // Matter.Body.applyForce(bodyA, bodyA.position, Matter.Vector.neg(force));
  450. // Matter.Body.applyForce(bodyB, bodyB.position, force);
  451. // }
  452. ]
  453. }
  454. });
  455. Matter.Body.setPosition(this.body, this.pos);
  456. // add init velocity
  457. this.setInitBodyVelocity()
  458. // console.log('concernementItem mass', this.body.mass);
  459. Matter.Composite.add(this.matterEngine.world, this.body);
  460. // console.log('concernement body', this.body);
  461. // listen for afterUpdate event from Matter.Engine object
  462. Matter.Events.on(this.matterEngine, "beforeUpdate", this.onBeforeEngineUpdate);
  463. Matter.Events.on(this.matterEngine, "afterUpdate", this.onAfterEngineUpdate);
  464. }
  465. },
  466. setInitBodyVelocity(){
  467. let delta = 50;
  468. Matter.Body.setVelocity(this.body, {
  469. x: -delta + Math.random()*delta*2,
  470. y: -delta + Math.random()*delta*2
  471. });
  472. },
  473. // PAPER OBJECTS
  474. initPaperObjects(){
  475. // the main paper group containing all paper graphical items for one concernement
  476. this.paper_main_object = new paper.Group({
  477. pivot: new paper.Point(this.pos),
  478. name: `main_${this.id}`,
  479. cid: this.cid,
  480. superposition_id: this.mapitem.superposition_ids[0] // TODO what to do with multiples superpositions ids
  481. });
  482. // the sub items for one concernement
  483. this.paper_main_object.addChild(this.setPaperContour());
  484. if (this.concernement.has_superpositions) {
  485. this.paper_main_object.addChild(this.setPaperEntitesSuperposees());
  486. }
  487. if (this.concernement.has_puissancedagir) {
  488. this.addNewPaperSymbolInstance('puissanceagir_icon', false, 0.7);
  489. }
  490. if (this.concernement.has_agissantes) {
  491. this.paper_main_object.addChild(this.setPaperAgissantesIcons());
  492. }
  493. if (this.concernement.has_doleance) {
  494. this.addNewPaperSymbolInstance('doleance_icon', false, 0.7);
  495. }
  496. this.initPaperEvents()
  497. },
  498. setPaperContents(){
  499. // trigered once opening tween is complete
  500. this.clearPaperContents();
  501. switch(this.map_mode){
  502. case 'terraindevie':
  503. this.addNewPaperSymbolInstance('boussole_bg', true);
  504. this.paper_main_object.addChild(this.setPaperEntites());
  505. break;
  506. case 'superposition':
  507. this.addNewPaperSymbolInstance('boussole_bg', true);
  508. break;
  509. case 'puissancedagir':
  510. this.addNewPaperSymbolInstance('puissanceagir_bg', true);
  511. this.paper_main_object.addChild(this.setPaperPuissanceagirBesoins());
  512. break;
  513. case 'action':
  514. this.addNewPaperSymbolInstance('boussole_bg', true);
  515. this.paper_main_object.addChild(this.setPaperAgissantes());
  516. break;
  517. case 'doleancer':
  518. this.addNewPaperSymbolInstance('doleance_bg');
  519. this.paper_main_object.addChild(this.setPaperDoleances());
  520. break;
  521. }
  522. },
  523. resetPaperActiveRevision(){
  524. console.log('resetPaperActiveRevision');
  525. this.getJarvisEnvelopeConvexe();
  526. // remove contours if already exists
  527. if (this.paper_main_object.children.contours) {
  528. this.paper_main_object.children.contours.remove();
  529. }
  530. // redraw contours
  531. this.paper_main_object.addChild(this.setPaperContour());
  532. // remove entites if already exists
  533. if (this.paper_main_object.children.entites) {
  534. this.paper_main_object.children.entites.remove();
  535. }
  536. // redraw entites
  537. this.paper_main_object.addChild(this.setPaperEntites());
  538. },
  539. clearPaperContents(){
  540. let clearable_children = ['boussole_bg', 'entites',
  541. 'puissanceagir_bg','puissanceagir_besoins',
  542. 'agissantes',
  543. 'doleance_bg', 'doleances'];
  544. clearable_children.forEach(child_name => {
  545. if (this.paper_main_object.children[child_name]) {
  546. this.paper_main_object.children[child_name].remove();
  547. }
  548. });
  549. },
  550. addNewPaperSymbolInstance(name, back, scale){
  551. let instance = new paper.SymbolItem(this.paper_symbol_definitions[name]); // , {x:0,y:0}
  552. instance.name = name;
  553. // instance.pivot = new paper.Point({x:0,y:0});
  554. instance.position = this.pos;
  555. let s = scale ? this.scale * scale : this.scale;
  556. instance.scale(s);
  557. // instance.locked = true;
  558. this.paper_main_object.addChild(instance);
  559. if (back) {
  560. this.paper_main_object.children[name].sendToBack();
  561. } else {
  562. this.paper_main_object.children[name].bringToFront();
  563. }
  564. },
  565. setPaperContour(){
  566. // console.log(`setPaperContour ${this.concernement.id}`);
  567. let getPaddedRoundedSegments = (b,a,c,d) => {
  568. const ac = { x: c.x - a.x, y: c.y - a.y } // get ac vecteur
  569. const lac = Math.sqrt(Math.pow(ac.x, 2) + Math.pow(ac.y, 2)); // get ac longueur ac
  570. const ab = { x: b.x - a.x, y: b.y - a.y } // get ab vecteur
  571. const lab = Math.sqrt(Math.pow(ab.x, 2) + Math.pow(ab.y, 2)); // get ab longeur
  572. const vab = { x: ab.x/lab, y: ab.y/lab } // get unit vecteur ab
  573. const an = { x: vab.x*lac, y: vab.y*lac } // get an vecteur
  574. const n = { x: a.x + an.x, y: a.y+an.y } // get n point
  575. const m = { x: (c.x + n.x)/2, y: (c.y + n.y)/2 } // get nc midle point
  576. const ma = { x:a.x - m.x, y: a.y - m.y } // get ma vecteur
  577. const lma = Math.sqrt(Math.pow(ma.x, 2)+Math.pow(ma.y, 2)) // get longeur m->a
  578. const vma = { x: ma.x/lma, y: ma.y/lma } // get ma vecteur unitaire
  579. // console.log(`vma x:${vma.x}, y:${vma.y}`);
  580. const pad = 4; // exterior padding
  581. // the final padded point
  582. const pa = [
  583. this.pos.x+(a.x+vma.x*pad)*this.scale,
  584. this.pos.y+(a.y+vma.y*pad)*this.scale
  585. ]
  586. // handles
  587. const delta = 0.05;
  588. // handle IN
  589. const hli = Math.abs(lab)*delta; // handle longeur
  590. const vnai = { x: -vma.y, y: vma.x } // get the ma normal unit vector IN
  591. const hai = [ vnai.x*hli, vnai.y*hli ]; // get the handleIn point
  592. // handle OUT
  593. const hlo = Math.abs(lac)*delta; // handle longeur
  594. const vnao = { x: vma.y, y: -vma.x } // get the ma normal vector Out
  595. const hao = [ vnao.x*hlo, vnao.y*hlo ]; // get the handleOut point
  596. return new paper.Segment({
  597. point: pa,
  598. handleIn: hai,
  599. handleOut: hao
  600. })
  601. }
  602. const first_point = getPaddedRoundedSegments(
  603. this.salientPoints[this.salientPoints.length-1].pos,
  604. this.salientPoints[0].pos,
  605. this.salientPoints[1].pos
  606. );
  607. let segments = [first_point];
  608. for (let j = 1; j < this.salientPoints.length-1; j++) {
  609. // segments.push([this.pos.x+this.salientPoints[j].pos.x*this.scale*gap, this.pos.y+this.salientPoints[j].pos.y*this.scale*gap])
  610. segments.push(getPaddedRoundedSegments(
  611. this.salientPoints[j-1].pos,
  612. this.salientPoints[j].pos,
  613. this.salientPoints[j+1].pos
  614. ))
  615. }
  616. const last_point = getPaddedRoundedSegments(
  617. this.salientPoints[this.salientPoints.length-2].pos,
  618. this.salientPoints[this.salientPoints.length-1].pos,
  619. this.salientPoints[0].pos
  620. );
  621. segments.push(last_point)
  622. segments.push(first_point)
  623. const contrs = new paper.Path({
  624. name: 'contours',
  625. segments: segments,
  626. fillColor: 'rgba(255,255,255,0.4)',
  627. // selected: true,
  628. strokeColor: '#fff',
  629. strokeWidth: 1,
  630. pivot: new paper.Point(this.pos),
  631. cid: this.cid
  632. });
  633. return contrs;
  634. },
  635. setPaperEntites(){
  636. let g = new paper.Group({
  637. pivot: new paper.Point(this.pos),
  638. name: 'entites'
  639. });
  640. // for (let i = 0; i < this.entites.length; i++) {
  641. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.active_revision].entites.length; i++) {
  642. let entite = this.concernement.revisions_byid[this.concernement.active_revision].entites[i];
  643. // use paper symbol
  644. let symbol_name = entite.entite ? entite.entite.agissante ? 'entite_action' : 'entite' : 'entite_hidden';
  645. let instance = new paper.SymbolItem(this.paper_symbol_definitions[symbol_name]);
  646. instance.name = 'entite';
  647. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  648. instance.scale(this.scale);
  649. instance.fillColor = '#000';
  650. instance.item_id = entite.entite ? entite.entite.id : null;
  651. instance.item_type = symbol_name;
  652. instance.is_symbol_instance = true;
  653. g.addChild(instance)
  654. }
  655. return g;
  656. },
  657. setPaperEntitesSuperposees(){
  658. // console.log('setPaperSuperpositions, superpositions', this.concernement.superpositions);
  659. let g = new paper.Group({
  660. pivot: new paper.Point(this.pos),
  661. name: 'entites_superposes'
  662. });
  663. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.active_revision].entites.length; i++) {
  664. let entite = this.concernement.revisions_byid[this.concernement.active_revision].entites[i];
  665. if (entite.entite // check if we have an entite object with all the contents
  666. && this.superposedEntitesIDsList.indexOf(entite.entite.id) >= 0) // check if entite id is in the list builded above
  667. {
  668. // console.log(`entite ${entite.entite.id}`, entite, entite.entite.superposition);
  669. // use paper symbol
  670. let instance = new paper.SymbolItem(this.paper_symbol_definitions['entite']);
  671. instance.name = 'entite';
  672. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  673. // instance.scale(this.scale);
  674. instance.scale(3);
  675. instance.fillColor = '#000';
  676. instance.item_id = entite.entite.id;
  677. instance.item_type = 'entite_superpose';
  678. instance.is_symbol_instance = true;
  679. g.addChild(instance)
  680. }
  681. }
  682. return g;
  683. },
  684. setPaperAgissantes(){
  685. console.log('setPaperAgissantes');
  686. let g = new paper.Group({
  687. pivot: new paper.Point(this.pos),
  688. name: 'agissantes'
  689. });
  690. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.revision_id].entites.length; i++) {
  691. let entite = this.concernement.revisions_byid[this.concernement.revision_id].entites[i];
  692. console.log('agissantes', entite);
  693. if (entite.entite && entite.entite.agissante) {
  694. let instance = new paper.SymbolItem(this.paper_symbol_definitions['entite_action']);
  695. instance.name = 'entite_action';
  696. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  697. instance.fillColor = '#000';
  698. // instance.scale(0.2);
  699. instance.scale(this.scale);
  700. instance.item_id = entite.entite.id;
  701. instance.item_type = 'entite_action';
  702. instance.is_symbol_instance = true;
  703. g.addChild(instance)
  704. }
  705. }
  706. return g;
  707. },
  708. setPaperAgissantesIcons(){
  709. let g = new paper.Group({
  710. pivot: new paper.Point(this.pos),
  711. name: 'agissantes_icons'
  712. });
  713. for (let i = 0; i < this.concernement.revisions_byid[this.concernement.revision_id].entites.length; i++) {
  714. let entite = this.concernement.revisions_byid[this.concernement.active_revision].entites[i];
  715. if (entite.entite && entite.entite.agissante) {
  716. let instance = new paper.SymbolItem(this.paper_symbol_definitions['entite_action_icon']);
  717. instance.name = 'entite_action';
  718. instance.position = new paper.Point([this.pos.x + entite.display.pos.x * this.scale, this.pos.y + entite.display.pos.y * this.scale]);
  719. instance.fillColor = '#000';
  720. // instance.scale(0.2);
  721. instance.scale(this.scale);
  722. instance.item_id = entite.entite.id;
  723. instance.item_type = 'entite_action';
  724. instance.is_symbol_instance = true;
  725. g.addChild(instance)
  726. }
  727. }
  728. return g;
  729. },
  730. setPaperPuissanceagirBesoins(){
  731. let g = new paper.Group({
  732. pivot: new paper.Point(this.pos),
  733. name: 'puissanceagir_besoins'
  734. });
  735. let res_fields = ['qui','quoi','ou','avec'];
  736. let arc = (360 / 16); // unit arc
  737. let r = (this.ray * this.scale)/5; // unit ray
  738. let br = r - r/3; // besoin ray
  739. for (let i = 0; i < this.concernement.besoins.length; i++) {
  740. let start_a = arc * i; // angle depart (for reponses)
  741. let center_a = start_a + arc/2; // angle central
  742. let x = Math.cos(center_a*(Math.PI/180)) * br;
  743. let y = Math.sin(center_a*(Math.PI/180)) * br;
  744. // use paper symbol
  745. let besoin = new paper.SymbolItem(this.paper_symbol_definitions['besoin']);
  746. besoin.position = new paper.Point([this.pos.x + x, this.pos.y + y]);
  747. besoin.scale(this.scale);
  748. besoin.item_id = this.concernement.besoins[i].id;
  749. besoin.item_cid = this.concernement.id;
  750. besoin.item_type = 'besoin';
  751. besoin.is_symbol_instance = true;
  752. console.log(`paper besoin id:${besoin.id}`);
  753. this.setBesoinPaperId(besoin.id, this.cid, this.concernement.besoins[i].id);
  754. g.addChild(besoin)
  755. let res_arc = arc / (1 + this.concernement.besoins[i].reponses.length); // unit arc for responses depending responses number
  756. for (let j = 0; j < this.concernement.besoins[i].reponses.length; j++) {
  757. let res_a = start_a + res_arc * (j+1); // angle for response line
  758. for (let f = 0; f < res_fields.length; f++) { // loop through all 4 fields, keep only the last one filled
  759. if( this.concernement.besoins[i].reponses[j][res_fields[f]] // if field filled
  760. && (f === res_fields.length -1 || !this.concernement.besoins[i].reponses[j][res_fields[f+1]]) // and is last field or last field filled
  761. ){
  762. let rr = this.ray * this.scale - r*f - r/2; // reponse field ray
  763. let rx = Math.cos(res_a*(Math.PI/180)) * rr;
  764. let ry = Math.sin(res_a*(Math.PI/180)) * rr;
  765. // use paper symbol
  766. let reponse = new paper.SymbolItem(this.paper_symbol_definitions['reponse']);
  767. reponse.position = new paper.Point([this.pos.x + rx, this.pos.y + ry]);
  768. reponse.scale(this.scale);
  769. reponse.item_id = this.concernement.besoins[i].reponses[j].id;
  770. reponse.item_bid = this.concernement.besoins[i].id;
  771. reponse.item_cid = this.concernement.id;
  772. reponse.item_type = 'reponse';
  773. reponse.is_symbol_instance = true;
  774. this.setBesoinPaperId(reponse.id, this.cid, this.concernement.besoins[i].id, this.concernement.besoins[i].reponses[j].id);
  775. g.addChild(reponse)
  776. }
  777. }
  778. }
  779. }
  780. return g;
  781. },
  782. setPaperDoleances(){
  783. let g = new paper.Group({
  784. pivot: new paper.Point({x:0,y:0}),
  785. name: `doleances`
  786. });
  787. this.concernement.doleances.forEach((d) => {
  788. g.addChild(this.setPaperDoleanceSteps(d))
  789. });
  790. return g;
  791. },
  792. setPaperDoleanceSteps(doleance){
  793. let g = new paper.Group({
  794. pivot: new paper.Point({x:0,y:0}),
  795. name: `doleance_${doleance.id}`,
  796. doleance_id: doleance.id
  797. });
  798. // let doleance = this.concernement.doleances[0];
  799. let all_fields = [
  800. [
  801. 'leprobleme',
  802. 'lenquete',
  803. {
  804. fieldname: 'groupesinterets',
  805. fields: [
  806. 'groupe_interets',
  807. 'accorder_interets',
  808. 'formuler',
  809. ]
  810. }
  811. ],
  812. [
  813. 'entite_addresse_doleance',
  814. 'comment_ennonce_doleance',
  815. 'aqui_addresse_doleance',
  816. {
  817. fieldname: 'reception_traitement',
  818. fields: [
  819. 'entite_adressee',
  820. 'doleance_formulee',
  821. 'traite_doleance',
  822. 'entite_recoit_doleance',
  823. ]
  824. }
  825. ],
  826. [
  827. 'entites_decisionnaires',
  828. 'decision_formule',
  829. {
  830. fieldname: 'mise_en_oeuvre_decision',
  831. fields: [
  832. 'entite_adresse_decision',
  833. 'formule_decision',
  834. 'entite_metenoeuvre_decisio',
  835. ]
  836. }
  837. ],
  838. [
  839. 'entite_adresse_application',
  840. 'aqui_adresse_decision',
  841. 'comment_formule_decision',
  842. {
  843. fieldname: 'receptions_et_applications',
  844. fields: [
  845. 'applique_decision',
  846. 'formule_decision_applic',
  847. 'entite_recoit_decision',
  848. ]
  849. },
  850. 'probleme_initial_resolu',
  851. 'oui_nouvelle_situation',
  852. 'non_adresse_doleance',
  853. ]
  854. ];
  855. var r = this.ray * this.scale * 0.8; // ray
  856. var dr = r/2; // demi ray
  857. // var pcr = 2*this.scale; // petits cercle rayon
  858. // https://fr.wikipedia.org/wiki/Trigonom%C3%A9trie#/media/Fichier:Unit_circle_angles_color.svg
  859. // https://fr.wikipedia.org/wiki/Identit%C3%A9_trigonom%C3%A9trique_pythagoricienne#Preuve_utilisant_le_cercle_unit%C3%A9
  860. // radians = degrees * (pi/180)
  861. // degrees = radians * (180/pi)
  862. // Points for 45° axes
  863. let m = Math.sin(45*(Math.PI/180)) * r; // x = y for rayon
  864. let n = Math.sin(45*(Math.PI/180)) * r/2; // x = y for demi rayon
  865. let o = Math.cos(22.5*(Math.PI/180)) * r; // x @ 22.5° for rayon
  866. let p = Math.sin(22.5*(Math.PI/180)) * r; // y @ 22.5° for rayon
  867. let o_d = Math.cos(22.5*(Math.PI/180)) * r/2; // x @ 22.5° for demi rayon
  868. let p_d = Math.sin(22.5*(Math.PI/180)) * r/2; // y @ 22.5° for demi rayon
  869. // let fontsize = 4;
  870. //
  871. // CAMENBERT STATIQUES
  872. //
  873. // l'enquete
  874. //
  875. // camenbert
  876. if (doleance.lenquete) {
  877. let cam = new paper.Path({
  878. strokeColor: '#fff',
  879. strokeWidth: 2,
  880. fillColor: "rgba(255, 255, 255, 0.4)",
  881. item_type: 'doleance_step',
  882. item_id: `lenquete`,
  883. did: doleance.id,
  884. field: 'lenquete',
  885. field_index: null
  886. });
  887. cam.add({x: this.pos.x , y: this.pos.y + dr});
  888. cam.lineTo({x: this.pos.x, y: this.pos.y + r});
  889. cam.arcTo({x: this.pos.x - p, y: this.pos.y + o}, {x: this.pos.x - m, y: this.pos.y + m});
  890. cam.lineTo({x: this.pos.x - n, y: this.pos.y + n});
  891. cam.arcTo({x: this.pos.x - p_d, y: this.pos.y + o_d}, {x: this.pos.x , y: this.pos.y + dr});
  892. // texte
  893. // enquete.addChild(new paper.PointText({
  894. // point: {
  895. // x:this.pos.x + Math.sin(22.5*(Math.PI/180)) * r*0.75,
  896. // y:this.pos.y + Math.cos(22.5*(Math.PI/180)) * r*0.75
  897. // },
  898. // content: doleance['lenquete'],
  899. // fontSize: fontsize,
  900. // fillColor: '#fff',
  901. // justification: 'center',
  902. // locked: true
  903. // }));
  904. g.addChild(cam);
  905. }
  906. //
  907. // probleme_initial_resolu
  908. //
  909. // camenbert
  910. if(doleance.probleme_initial_resolu === 0 || doleance.probleme_initial_resolu === 1){
  911. let rescam = new paper.Path({
  912. strokeColor: '#fff',
  913. strokeWidth: 2,
  914. fillColor: "rgba(255, 255, 255, 0.4)",
  915. closed: true,
  916. item_type: 'doleance_step',
  917. item_id: `probleme_initial_resolu`,
  918. did: doleance.id,
  919. field: 'probleme_initial_resolu',
  920. field_index: null
  921. });
  922. rescam.add({x: this.pos.x + n, y: this.pos.y + n});
  923. rescam.lineTo({x: this.pos.x + m , y: this.pos.y + m});
  924. rescam.arcTo({x: this.pos.x + p, y: this.pos.y + o}, {x: this.pos.x, y: this.pos.y + r});
  925. rescam.lineTo({x: this.pos.x, y: this.pos.y + dr});
  926. rescam.arcTo({x: this.pos.x + p_d, y: this.pos.y + o_d}, {x: this.pos.x + n, y: this.pos.y + n});
  927. // texte
  928. // resolution.addChild(new paper.PointText({
  929. // point: {
  930. // x:this.pos.x - Math.sin(22.5*(Math.PI/180)) * r*0.75,
  931. // y:this.pos.y + Math.cos(22.5*(Math.PI/180)) * r*0.75
  932. // },
  933. // content: doleance['probleme_initial_resolu'] ? doleance['oui_nouvelle_situation'] : doleance['non_adresse_doleance'],
  934. // fontSize: fontsize,
  935. // fillColor: '#fff',
  936. // justification: 'center'
  937. // }));
  938. g.addChild(rescam)
  939. }
  940. //
  941. // MULTIPLE FIELDS
  942. //
  943. let multiple_fields = [
  944. { field_name: 'groupesinterets', arc: 45, decalage: -45 },
  945. { field_name: 'reception_traitement', arc: 90, decalage: -90 },
  946. { field_name: 'mise_en_oeuvre_decision', arc: 90, decalage: -180 },
  947. { field_name: 'receptions_et_applications', arc: 45, decalage: 90 }
  948. ]
  949. multiple_fields.forEach((mf, j) => {
  950. for (let i = 0, l = doleance[mf.field_name].length, a = mf.arc/l; i < l; i++) {
  951. // let gi = new paper.Group({
  952. // item_type: 'doleance_step',
  953. // item_id: 'lenquete',
  954. // item_field: mf.field_name,
  955. // item_index: i
  956. // });
  957. //camenbert
  958. let x1= this.pos.x + Math.sin((mf.decalage- a*i)*(Math.PI/180)) * dr,
  959. y1= this.pos.y + Math.cos((mf.decalage- a*i)*(Math.PI/180)) * dr;
  960. let x2= this.pos.x + Math.sin((mf.decalage- a*i)*(Math.PI/180)) * r,
  961. y2= this.pos.y + Math.cos((mf.decalage- a*i)*(Math.PI/180)) * r;
  962. let x3= this.pos.x + Math.sin((mf.decalage- a*(i+1))*(Math.PI/180)) * r,
  963. y3= this.pos.y + Math.cos((mf.decalage- a*(i+1))*(Math.PI/180)) * r;
  964. let x3t= this.pos.x + Math.sin((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r,
  965. y3t= this.pos.y + Math.cos((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r;
  966. let x4= this.pos.x + Math.sin((mf.decalage- a*(i+1))*(Math.PI/180)) * dr,
  967. y4= this.pos.y + Math.cos((mf.decalage- a*(i+1))*(Math.PI/180)) * dr;
  968. let x4t= this.pos.x + Math.sin((mf.decalage- a*(i+0.5))*(Math.PI/180)) * dr,
  969. y4t= this.pos.y + Math.cos((mf.decalage- a*(i+0.5))*(Math.PI/180)) * dr;
  970. let x5= this.pos.x + Math.sin((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r*0.75,
  971. y5= this.pos.y + Math.cos((mf.decalage- a*(i+0.5))*(Math.PI/180)) * r*0.75;
  972. let p = new paper.Path({
  973. strokeColor: '#fff',
  974. strokeWidth: 2,
  975. fillColor: "rgba(255, 255, 255, 0.4)",
  976. item_type: 'doleance_step',
  977. item_id: `${mf.field_name}-${i}`,
  978. did: doleance.id,
  979. field: mf.field_name,
  980. field_index: i
  981. });
  982. p.add([x1,y1]);
  983. p.lineTo([x2,y2]);
  984. p.arcTo([x3t,y3t], [x3,y3]);
  985. p.lineTo([x4,y4]);
  986. p.arcTo([x4t,y4t], [x1,y1]);
  987. g.addChild(p);
  988. // gi.addChild(p);
  989. // // text
  990. // gi.addChild(new paper.PointText({
  991. // point: {x:x5,y:y5},
  992. // content: `${j}-${i}`,
  993. // fontSize: fontsize,
  994. // fillColor: '#fff',
  995. // justification: 'center'
  996. // }))
  997. // g.addChild(gi)
  998. }
  999. });
  1000. // POINTS CARDINAUX
  1001. // leprobleme
  1002. if (doleance.leprobleme) {
  1003. g.addChild(new paper.Path.Circle({
  1004. center: [this.pos.x, this.pos.y + r],
  1005. radius: 3 * this.scale,
  1006. style: {
  1007. strokeColor: '#fff',
  1008. strokeWidth: 2,
  1009. fillColor: "rgba(255, 255, 255, 0.9)",
  1010. },
  1011. item_type: 'doleance_step',
  1012. item_id: `leprobleme`,
  1013. did: doleance.id,
  1014. field: 'leprobleme'
  1015. }));
  1016. }
  1017. // adresse de la doleance
  1018. if (doleance.entite_addresse_doleance || doleance.aqui_addresse_doleance || doleance.comment_ennonce_doleance) {
  1019. g.addChild(new paper.Path.Circle({
  1020. center: [this.pos.x - r, this.pos.y],
  1021. radius: 3 * this.scale,
  1022. style: {
  1023. strokeColor: '#fff',
  1024. strokeWidth: 2,
  1025. fillColor: "rgba(255, 255, 255, 0.9)",
  1026. },
  1027. item_type: 'doleance_step',
  1028. item_id: `adresse_de_la_doleance`,
  1029. did: doleance.id,
  1030. field: 'adresse_de_la_doleance'
  1031. }));
  1032. }
  1033. // decision
  1034. if (doleance.entites_decisionnaires || doleance.decision_formule) {
  1035. g.addChild(new paper.Path.Circle({
  1036. center: [this.pos.x, this.pos.y - r],
  1037. radius: 3 * this.scale,
  1038. style: {
  1039. strokeColor: '#fff',
  1040. strokeWidth: 2,
  1041. fillColor: "rgba(255, 255, 255, 0.9)",
  1042. },
  1043. item_type: 'doleance_step',
  1044. item_id: `decision`,
  1045. did: doleance.id,
  1046. field: 'decision'
  1047. }));
  1048. }
  1049. // adresse_de_la_decision
  1050. if (doleance.entite_adresse_application || doleance.aqui_adresse_decision || doleance.comment_formule_decision) {
  1051. g.addChild(new paper.Path.Circle({
  1052. center: [this.pos.x + r, this.pos.y],
  1053. radius: 3 * this.scale,
  1054. style: {
  1055. strokeColor: '#fff',
  1056. strokeWidth: 2,
  1057. fillColor: "rgba(255, 255, 255, 0.9)",
  1058. },
  1059. item_type: 'doleance_step',
  1060. item_id: `adresse_de_la_decision`,
  1061. did: doleance.id,
  1062. field: 'adresse_de_la_decision'
  1063. }));
  1064. }
  1065. return g;
  1066. },
  1067. // PAPER VISIBILITY
  1068. handlePaperVisibilityOnBeforeOpen(){
  1069. // agissantes
  1070. if (this.concernement.has_agissantes && this.map_mode === "action") {
  1071. if (!this.is_open) {
  1072. this.paper_main_object.children.agissantes_icons.visible = true;
  1073. } else {
  1074. this.paper_main_object.children.agissantes_icons.visible = false;
  1075. }
  1076. }
  1077. // superposition
  1078. // scale down superposed entites on open
  1079. let entites_superposes = this.paper_main_object.children['entites_superposes'];
  1080. // console.log('entites_superposes.children', entites_superposes.children);
  1081. if(entites_superposes){
  1082. for(let paper_item of entites_superposes.children) {
  1083. // paper_item.definition = this.paper_symbol_definitions.entite_hover;
  1084. paper_item.scale(0.25)
  1085. }
  1086. }
  1087. },
  1088. handlePaperVisibilityOnOpened(){},
  1089. handlePaperVisibilityOnBeforeClose(){
  1090. // superposition
  1091. // scale up superposed entites on open
  1092. let entites_superposes = this.paper_main_object.children['entites_superposes'];
  1093. // console.log('entites_superposes.children', entites_superposes.children);
  1094. if(entites_superposes){
  1095. for(let paper_item of entites_superposes.children) {
  1096. // paper_item.definition = this.paper_symbol_definitions.entite_hover;
  1097. paper_item.scale(4)
  1098. }
  1099. }
  1100. },
  1101. handlePaperVisibilityOnClosed(){
  1102. // agissantes
  1103. if (this.concernement.has_agissantes && this.map_mode === "action") {
  1104. if (!this.is_open) {
  1105. this.paper_main_object.children.agissantes_icons.visible = true;
  1106. } else {
  1107. this.paper_main_object.children.agissantes_icons.visible = false;
  1108. }
  1109. }
  1110. },
  1111. handlePaperVisibilityOnMapMode(){},
  1112. handlePaperVisibilityOnAfterEnginUpdate(){
  1113. // contours focused
  1114. if (!this.isFocused()){
  1115. this.paper_main_object.children['contours'].fillColor = "rgba(255,255,255,0.1)"; //this.mapitem.clone ? "rgba(255,0,0,0.1)" : "rgba(255,255,255,0.1)";
  1116. }else{
  1117. this.paper_main_object.children['contours'].fillColor = "rgba(255,255,255,0.4)"; //this.mapitem.clone ? "rgba(255,0,0,0.4)" : "rgba(255,255,255,0.4)";
  1118. if (this.is_hover) {
  1119. this.paper_main_object.children['contours'].strokeColor = "#01ffe2";
  1120. this.paper_main_object.children['contours'].strokeWidth = 2;
  1121. }else{
  1122. this.paper_main_object.children['contours'].strokeColor = "#fff";
  1123. this.paper_main_object.children['contours'].strokeWidth = 1;
  1124. }
  1125. }
  1126. // contours visibility
  1127. if (!this.is_open
  1128. || (this.is_open && this.map_mode !== "puissancedagir" && this.map_mode !== "doleancer")) {
  1129. this.paper_main_object.children['contours'].visible = true;
  1130. } else {
  1131. this.paper_main_object.children['contours'].visible = false;
  1132. }
  1133. // proximite
  1134. // superposition
  1135. if (this.concernement.has_superpositions) {
  1136. if (this.map_mode === "superposition") {
  1137. this.paper_main_object.children.entites_superposes.visible = true;
  1138. // highlight of entite part of opened superposition
  1139. let group = this.paper_main_object.children['entites_superposes'];
  1140. if(group){
  1141. if (this.$route.query.superposition_id) {
  1142. let superposition_id = this.$route.query.superposition_id;
  1143. if(superposition_id){
  1144. let ids = superposition_id.match(/(\d+)_(\d+)__(\d+)_(\d+)/i)
  1145. group.children.forEach((item) => {
  1146. if ( (this.cid === parseInt(ids[1]) && item.item_id === parseInt(ids[2]))
  1147. || (this.cid === parseInt(ids[3]) && item.item_id === parseInt(ids[4])) ) {
  1148. item.definition = this.paper_symbol_definitions.entite_hover;
  1149. if(!item.focused){
  1150. item.scale(2)
  1151. item.focused = true;
  1152. }
  1153. } else if(!this.is_hover) {
  1154. item.definition = this.paper_symbol_definitions.entite;
  1155. if (item.focused) {
  1156. item.scale(0.5)
  1157. item.focused = false;
  1158. }
  1159. }
  1160. })
  1161. }
  1162. }else{
  1163. group.children.forEach((item) => {
  1164. if(!this.is_hover) {
  1165. item.definition = this.paper_symbol_definitions.entite;
  1166. if (item.focused) {
  1167. item.scale(0.5)
  1168. item.focused = false;
  1169. }
  1170. }
  1171. })
  1172. }
  1173. }
  1174. } else {
  1175. this.paper_main_object.children.entites_superposes.visible = false;
  1176. }
  1177. }
  1178. // puissance d'agir
  1179. if (this.concernement.has_puissancedagir) {
  1180. if (this.map_mode === "puissancedagir") {
  1181. if (!this.is_open) {
  1182. this.paper_main_object.children.puissanceagir_icon.visible = true; // if not opened and has_puissancedagir draw the puissance d'agir icone
  1183. } else {
  1184. this.paper_main_object.children.puissanceagir_icon.visible = false;
  1185. }
  1186. } else {
  1187. this.paper_main_object.children.puissanceagir_icon.visible = false;
  1188. }
  1189. }
  1190. // agissantes
  1191. if (this.concernement.has_agissantes) {
  1192. if (this.map_mode !== "action") {
  1193. this.paper_main_object.children.agissantes_icons.visible = false;
  1194. } else if(!this.is_open && !this.is_closing){
  1195. this.paper_main_object.children.agissantes_icons.visible = true;
  1196. }
  1197. }
  1198. // doleance
  1199. if (this.concernement.has_doleance) {
  1200. if (this.map_mode === "doleancer") {
  1201. if (!this.is_open) {
  1202. this.paper_main_object.children.doleance_icon.visible = true;
  1203. } else {
  1204. this.paper_main_object.children.doleance_icon.visible = false;
  1205. // display the right (opened) doleance
  1206. this.concernement.doleances.forEach((d) => {
  1207. this.paper_main_object.children.doleances.children[`doleance_${d.id}`].visible = d.id === this.concernement.opened_doleance.id;
  1208. })
  1209. }
  1210. } else {
  1211. this.paper_main_object.children.doleance_icon.visible = false;
  1212. }
  1213. }
  1214. // focus on opened entite
  1215. if (this.is_open && this.opened_entite_id && (this.map_mode === 'terraindevie' || this.map_mode === 'action')) {
  1216. let group = this.map_mode === 'terraindevie' ? this.paper_main_object.children['entites'] : this.paper_main_object.children['agissantes'];
  1217. if(group){
  1218. group.children.forEach((item) => {
  1219. if (item.item_id === this.opened_entite_id) {
  1220. item.definition = item.item_type === 'entite' ? this.paper_symbol_definitions.entite_hover : this.paper_symbol_definitions.entite_action_hover;
  1221. } else {
  1222. if (!this.hover_elmt || item.item_id !== this.hover_elmt.id) {
  1223. item.definition = item.item_type === 'entite' ? this.paper_symbol_definitions.entite : this.paper_symbol_definitions.entite_action;
  1224. }
  1225. }
  1226. })
  1227. }
  1228. }
  1229. },
  1230. onIsHover(){
  1231. // handle layer z-index
  1232. if (this.is_hover) {
  1233. this.paper_main_object.bringToFront();
  1234. } else {
  1235. // mapitem can be hover while an other mapitem is open if it is superposed (superposition) to the currently opened mapitem
  1236. // in this case don't send it back
  1237. if (!this.opened_concernement) {
  1238. this.paper_main_object.sendToBack();
  1239. }
  1240. }
  1241. // hightlight superposed entites on focus
  1242. let entites_superposes = this.paper_main_object.children['entites_superposes'];
  1243. // console.log('entites_superposes.children', entites_superposes.children);
  1244. if(entites_superposes){
  1245. for(let paper_item of entites_superposes.children) {
  1246. if (this.is_hover) {
  1247. paper_item.definition = this.paper_symbol_definitions.entite_hover;
  1248. // paper_item.scale(2)
  1249. } else {
  1250. paper_item.definition = this.paper_symbol_definitions.entite;
  1251. // paper_item.scale(0.5)
  1252. }
  1253. }
  1254. }
  1255. },
  1256. // PAPER EVENTS
  1257. initPaperEvents(){
  1258. this.paper_main_object.onMouseLeave = function(event){
  1259. if (!this.opened_concernement && this.isFocused()) { // only if no concernement is opened
  1260. this.resetHoverElmt();
  1261. document.body.style.cursor = "auto";
  1262. }
  1263. }.bind(this);
  1264. this.paper_main_object.onMouseMove = function(event){
  1265. console.log(`onmousemove ${this.id}`, this.cartouch_is_opened);
  1266. // prevent hover map item mouse event if cartouch is opened
  1267. if (this.cartouch_is_opened && this.map_mode !== "superposition") return;
  1268. if (!this.is_open) {
  1269. if (!this.opened_concernement) { // only if no concernement is opened and is this focused
  1270. if(this.isFocused()){
  1271. if (this.map_mode === 'superposition') {
  1272. // get the superposed entite
  1273. this.setHoverElmt({
  1274. type: 'superposition',
  1275. id: this.id,
  1276. cid: this.cid,
  1277. eids: this.superposedEntitesIDsList
  1278. });
  1279. } else{
  1280. this.setHoverElmt({
  1281. type: 'concernement',
  1282. id: this.id,
  1283. cid: this.cid
  1284. });
  1285. }
  1286. document.body.style.cursor = "pointer";
  1287. }
  1288. } else if (this.map_mode === 'superposition'){
  1289. // if this mapitem is superposed to the opened mapitem
  1290. if(this.opened_concernement.all_superposed_concernements_id.indexOf(this.cid) >= 0){
  1291. this.setHoverElmt({
  1292. type: 'superposition',
  1293. id: this.id,
  1294. cid: this.cid,
  1295. eids: this.superposedEntitesIDsList
  1296. });
  1297. document.body.style.cursor = "pointer";
  1298. }
  1299. }
  1300. } else {
  1301. // lets define some options regarding the map_mode
  1302. let paper_group_tohit;
  1303. switch (this.map_mode) {
  1304. case "terraindevie":
  1305. paper_group_tohit = this.paper_main_object.children['entites'];
  1306. break;
  1307. case "superposition":
  1308. paper_group_tohit = this.paper_main_object.children['entites_superposes'];
  1309. break;
  1310. case "action":
  1311. paper_group_tohit = this.paper_main_object.children['agissantes'];
  1312. break;
  1313. case "puissancedagir":
  1314. paper_group_tohit = this.paper_main_object.children['puissanceagir_besoins'];
  1315. break;
  1316. case "doleancer":
  1317. if(this.paper_main_object.children['doleances']){
  1318. paper_group_tohit = this.paper_main_object.children['doleances'].children[`doleance_${this.concernement.opened_doleance.id}`];
  1319. }
  1320. break;
  1321. }
  1322. let result = paper_group_tohit ? paper_group_tohit.hitTest(event.point) : null;
  1323. // console.log('move result', result);
  1324. if (result && result.item.item_id) {
  1325. // console.log('move has result', result);
  1326. let new_hover_elmt = {
  1327. paper_id: result.item.id,
  1328. type: result.item.item_type,
  1329. id: result.item.item_id
  1330. };
  1331. switch (result.item.item_type) {
  1332. case "besoin":
  1333. new_hover_elmt.no_popup = true;
  1334. break;
  1335. case "reponse":
  1336. new_hover_elmt.bid = result.item.item_bid;
  1337. new_hover_elmt.cid = result.item.item_cid;
  1338. new_hover_elmt.no_popup = true;
  1339. break;
  1340. }
  1341. if (!this.hover_elmt || new_hover_elmt.paper_id !== this.hover_elmt.paper_id) {
  1342. // console.log(`before setHoverElmt ${this.id}`);
  1343. this.setHoverElmt(new_hover_elmt);
  1344. }
  1345. document.body.style.cursor = "pointer";
  1346. } else {
  1347. // console.log('move no result');
  1348. this.resetHoverElmt();
  1349. document.body.style.cursor = "auto";
  1350. }
  1351. }
  1352. }.bind(this);
  1353. this.paper_main_object.onClick = async function(event){
  1354. console.log('paper concernement onClick');
  1355. // prevent hover map item mouse event if cartouch is opened
  1356. if (this.cartouch_is_opened) return;
  1357. if (!this.is_open) { // si ce concernement n'est pas ouvet
  1358. console.log('mapitem is NOT opened');
  1359. if (!this.opened_concernement) { // si aucun concernement n'est ouvert
  1360. console.log(`Open me ${this.id}`);
  1361. // push route (keep the hash for map_mode)
  1362. // wait for routing to be finished before opening the mapItem
  1363. await this.$router.push({
  1364. name: 'concernement',
  1365. params: {cid: parseInt(this.cid)},
  1366. query: {
  1367. mapitemid: this.id,
  1368. superposition_id: this.mapitem.superposition_ids[0]
  1369. },
  1370. hash: `#${this.map_mode}`
  1371. });
  1372. // open/close all concernements
  1373. this.openCloseConcernements(this.cid, this.id)
  1374. // reset the mousehover
  1375. this.resetHoverElmt();
  1376. } else if (this.map_mode === 'superposition'){
  1377. // if this mapitem is superposed to the opened mapitem
  1378. if(this.opened_concernement.all_superposed_concernements_id.indexOf(this.cid) >= 0){
  1379. // push route (keep the hash for map_mode)
  1380. // wait for routing to be finished before opening the mapItem
  1381. console.log('click on superposed this.mapitem.superposition_ids', this.mapitem.superposition_ids);
  1382. await this.$router.push({
  1383. name: 'concernement',
  1384. params: {cid: this.opened_concernement.cid},
  1385. query: {
  1386. mapitemid: this.opened_concernement.opened_mapitem_id,
  1387. superposition_id: this.mapitem.superposition_ids[0]
  1388. },
  1389. hash: `#${this.map_mode}`
  1390. });
  1391. }
  1392. }
  1393. } else { // si ce concernement est ouvert
  1394. console.log('mapitem is opened');
  1395. // lets define some options regarding the map_mode
  1396. let group_to_hit = null;
  1397. switch (this.map_mode) {
  1398. case "terraindevie":
  1399. group_to_hit = this.paper_main_object.children['entites'];
  1400. break;
  1401. case "superposition":
  1402. group_to_hit = this.paper_main_object.children['entites_superposes'];
  1403. break;
  1404. case "action":
  1405. group_to_hit = this.paper_main_object.children['agissantes'];
  1406. break;
  1407. case "doleancer":
  1408. group_to_hit = this.paper_main_object.children['doleances'].children[`doleance_${this.concernement.opened_doleance.id}`];
  1409. break;
  1410. }
  1411. if (group_to_hit) {
  1412. let result = group_to_hit.hitTest(event.point);
  1413. console.log('click result', result);
  1414. if (result) {
  1415. switch (this.map_mode) {
  1416. case "terraindevie":
  1417. case "superposition":
  1418. case "action":
  1419. // we have clicked on an entite
  1420. this.$router.push({
  1421. name: 'concernement',
  1422. params: {cid: this.cid, eid: result.item.item_id},
  1423. query: {
  1424. mapitemid: this.id,
  1425. superposition_id: this.mapitem.superposition_ids[0]
  1426. },
  1427. hash: `#${this.map_mode}`,
  1428. });
  1429. break;
  1430. case "doleancer":
  1431. this.setOpenedDoleanceField(this.cid, result.item.did, result.item.field, result.item.field_index);
  1432. break;
  1433. }
  1434. } else {
  1435. // otherwise we close the entite and come back to the concernement
  1436. this.$router.push({
  1437. name: 'concernement',
  1438. hash: `#${this.map_mode}`,
  1439. params: {id: this.cid, mapitemid: this.id}
  1440. });
  1441. // reset the mousehover
  1442. this.resetHoverElmt();
  1443. }
  1444. }
  1445. }
  1446. }.bind(this);
  1447. },
  1448. resetHoverElmt(){
  1449. // console.log('resetHoverElmt');
  1450. setTimeout(()=>{
  1451. this.setHoverElmt(null);
  1452. }, 100);
  1453. },
  1454. // OPEN / CLOSE (with tween)
  1455. openClose(open) { // async
  1456. // await nextTick(); // not working
  1457. console.log(`ConcernementsMapItem ${this.id} openClose: ${open}`);
  1458. if (this.tween) {
  1459. this.tween.stop();
  1460. }
  1461. if (open) {
  1462. this.is_opening = true;
  1463. // create the paper objects to display (like entite, besoin, etc)
  1464. this.setPaperContents();
  1465. this.handlePaperVisibilityOnBeforeOpen();
  1466. // calcul opened size regarding window size and surounding contents
  1467. let header = document.querySelector('header#header');
  1468. let header_height = header.clientHeight;
  1469. let map_nav = document.querySelector('nav#map-nav');
  1470. let map_nav_height = map_nav.clientHeight;
  1471. let s_h = (this.canvas.height - header_height - map_nav_height) / (this.ray*2*1.15);
  1472. let s_w = (this.canvas.width - this.cartouch_width) / (this.ray*2*1.7);
  1473. let s = Math.min(s_h, s_w)
  1474. // create once the opening tweening
  1475. this.tween = new Tween.Tween({s: this.scale, x: this.pos.x, y: this.pos.y, o: 0})
  1476. .to({
  1477. s: s,
  1478. x: (this.canvas.width - this.cartouch_width) / 2,
  1479. y: this.canvas.height / 2,
  1480. o: 0.8
  1481. }, 800)
  1482. .onUpdate((obj) => {
  1483. // https://github.com/liabru/matter-js/issues/986#issuecomment-812488873
  1484. // revert to the original size (by reverting the previous scale)
  1485. // Matter.Body.scale(this.body, 1 / this.scale, 1 / this.scale)
  1486. this.paper_main_object.scale(1 / this.scale);
  1487. // then scale again to new scale
  1488. // Matter.Body.scale(this.body, obj.s, obj.s)
  1489. this.paper_main_object.scale(obj.s);
  1490. // update superposition constraints points poisitions
  1491. if (this.concernement.superposition_constraints_id
  1492. && this.concernement.superposition_constraints_id[this.id]
  1493. && this.concernement.superposition_constraints_id[this.id].length)
  1494. {
  1495. // get all the constraints of the world
  1496. let all_constrains = Matter.Composite.allConstraints(this.matterEngine.world);
  1497. // loop through all constraint ids recorded in the concernement
  1498. // get only the constraint of this concernement mapitem
  1499. for(let constraint_id of this.concernement.superposition_constraints_id[this.id]) {
  1500. // get the right constraint object from matter
  1501. let constraint;
  1502. for (const c of all_constrains) {
  1503. if (c.id === constraint_id) {
  1504. constraint = c;
  1505. break;
  1506. }
  1507. }
  1508. if (constraint) {
  1509. // tween the constraint point
  1510. let ab = this.cid === constraint.concernementA.id ? 'A' : 'B';
  1511. let point = constraint[`point${ab}`];
  1512. // revert to the original point
  1513. let oripoint = Matter.Vector.create(point.x / this.scale, point.y / this.scale)
  1514. // newpoint from original point
  1515. let newpoint = Matter.Vector.create(oripoint.x * obj.s, oripoint.y * obj.s)
  1516. constraint[`point${ab}`] = newpoint;
  1517. }
  1518. }
  1519. }
  1520. // record new scale
  1521. this.prev_scale = this.scale;
  1522. this.scale = obj.s;
  1523. this.opacity = obj.o;
  1524. // console.log('tween update obj.s', obj.s);
  1525. this.pos = {x:obj.x, y:obj.y};
  1526. Matter.Body.setPosition(this.body, this.pos);
  1527. })
  1528. .onComplete((obj) => {
  1529. // console.log('tween complete obj.s', obj.s);
  1530. // record tween one last time
  1531. this.prev_scale = this.scale = obj.s;
  1532. this.opacity = obj.o;
  1533. this.pos = {x:obj.x, y:obj.y};
  1534. Matter.Body.setPosition(this.body, this.pos);
  1535. this.handlePaperVisibilityOnOpened();
  1536. // fix the concernement position with a constraint
  1537. this.constraint = Matter.Constraint.create({
  1538. pointA: this.pos,
  1539. bodyB: this.body,
  1540. stiffness: 1,
  1541. damping: 0,
  1542. length: 0
  1543. });
  1544. Matter.Composite.add(this.matterEngine.world, [this.body, this.constraint]);
  1545. // paper bring to front
  1546. // this.paper_main_object.bringToFront();
  1547. this.paper_main_object.sendToBack();
  1548. this.is_opening = false;
  1549. });
  1550. // recreate the matter engine event to get it a the end of the events stack
  1551. Matter.Events.off(this.matterEngine, "afterUpdate", this.onAfterEngineUpdate);
  1552. Matter.Events.on(this.matterEngine, "afterUpdate", this.onAfterEngineUpdate);
  1553. } else {
  1554. // closing
  1555. this.is_closing = true;
  1556. if(this.constraint){
  1557. Matter.Composite.remove(this.matterEngine.world, this.constraint);
  1558. }
  1559. this.concernement.active_revision = this.concernement.revision_id;
  1560. this.handlePaperVisibilityOnBeforeClose();
  1561. // this.setOpenedRecit(null);
  1562. // create once the closing tween
  1563. this.tween = new Tween.Tween({s: this.scale, o: 1})
  1564. .to({s: 1, o: 0}, 500)
  1565. .onUpdate((obj) => {
  1566. // https://github.com/liabru/matter-js/issues/986#issuecomment-812488873
  1567. // revert to the original size (by reverting the previous scale)
  1568. // INFO we dont need to sacle the matter body AND it may fix the montgolfière bug
  1569. // TODO find another way to increase the mass
  1570. // Matter.Body.scale(this.body, 1 / this.scale, 1 / this.scale)
  1571. this.paper_main_object.scale(1 / this.scale);
  1572. // then scale again to new scale
  1573. // Matter.Body.scale(this.body, obj.s, obj.s)
  1574. this.paper_main_object.scale(obj.s);
  1575. // update superposition constraints points positions
  1576. if (this.concernement.superposition_constraints_id
  1577. && this.concernement.superposition_constraints_id[this.id]
  1578. && this.concernement.superposition_constraints_id[this.id].length)
  1579. {
  1580. // get all the constraints of the world
  1581. let all_constrains = Matter.Composite.allConstraints(this.matterEngine.world);
  1582. // loop through all constraint ids recorded in the concernement
  1583. // get only the constraint of this concernement mapitem
  1584. for(let constraint_id of this.concernement.superposition_constraints_id[this.id]) {
  1585. // get the right constraint object from matter
  1586. let constraint;
  1587. for (const c of all_constrains) {
  1588. if (c.id === constraint_id) {
  1589. constraint = c;
  1590. break;
  1591. }
  1592. }
  1593. if (constraint) {
  1594. // tween the constraint point
  1595. let ab = this.cid === constraint.concernementA.id ? 'A' : 'B';
  1596. let point = constraint[`point${ab}`];
  1597. // revert to the original point
  1598. let oripoint = Matter.Vector.create(point.x / this.scale, point.y / this.scale)
  1599. // newpoint from original point
  1600. let newpoint = Matter.Vector.create(oripoint.x * obj.s, oripoint.y * obj.s)
  1601. constraint[`point${ab}`] = newpoint;
  1602. }
  1603. }
  1604. }
  1605. // record new scale
  1606. this.prev_scale = this.scale;
  1607. this.scale = obj.s;
  1608. this.opacity = obj.o;
  1609. })
  1610. .onComplete((obj) => {
  1611. this.prev_scale = this.scale = 1;
  1612. this.handlePaperVisibilityOnClosed();
  1613. this.clearPaperContents();
  1614. this.is_closing = false;
  1615. });
  1616. }
  1617. this.tween.easing(Tween.Easing.Quadratic.InOut).start();
  1618. },
  1619. // ENGINE UPDATE
  1620. onBeforeEngineUpdate (event) {
  1621. // update the opening/closing tweening
  1622. if (this.tween) {
  1623. this.tween.update();
  1624. }
  1625. if (this.opened_concernement) {
  1626. // console.log("try to push aside", this.opened_concernement.opened_mapitem_id, this.id, this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id]);
  1627. // console.log(this.id, this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id].indexOf(this.id));
  1628. if (this.opened_concernement.opened_mapitem_id !== this.id) {
  1629. // push all aside mapitems not superposed the the opened mapitem
  1630. let pushaside = true;
  1631. // BUT NOT push aside mapitems superposed to superposed mapitems
  1632. // opened_mapitem <-- superposed_mapitems <-- superposed_mapitem
  1633. if (this.opened_concernement.superposed_mapitem_id_by_mapitem_id
  1634. && this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id])
  1635. { // if opened mapitem has superposed mapitems
  1636. let superposed_ids = this.opened_concernement.superposed_mapitem_id_by_mapitem_id[this.opened_concernement.opened_mapitem_id]
  1637. if (superposed_ids.indexOf(this.id) >= 0) { //this mapitem is directly superposed to the opened mapitem
  1638. pushaside = false;
  1639. } else { // else we look for second stage of the rockette ... superposed to superposed to opened
  1640. superposed_ids.forEach(mapitem_id => { // for each superposed map_item, check if this mapitem is in their superposed
  1641. let mapitem = this.allMapItems_byid[mapitem_id]; // get the superposed (stage 1) mapitem
  1642. mapitem.superposition_ids.forEach(sup_id => { // for each superposed (stage 2) of the superposed (stage 1)
  1643. if (this.mapitem.superposition_ids.indexOf(sup_id) >= 0) {
  1644. pushaside = false;
  1645. }
  1646. });
  1647. });
  1648. }
  1649. }
  1650. if (pushaside) {
  1651. this.pushAside()
  1652. }
  1653. }
  1654. } else if (!this.is_hover){
  1655. if (this.map_mode === 'proximite'
  1656. || this.map_mode === 'superposition'
  1657. || this.map_mode === 'puissancedagir'
  1658. || this.map_mode === 'action'
  1659. || this.map_mode === 'doleancer'){ // apply focus forces : move unfocused on the sides and focused on the center
  1660. this.applyFocusForces(); //
  1661. } else {
  1662. this.applyNormalForces(); // if terrain de vie apply force to gently reject items from the sides and so create a continuasly mvmt
  1663. }
  1664. } else {
  1665. // stop movement if is mouse hover
  1666. Matter.Body.setVelocity(this.body, {x:0, y:0})
  1667. }
  1668. // reset all matter rotation forces otherwise items will spin when colide
  1669. Matter.Body.setAngle(this.body, 0);
  1670. Matter.Body.setAngularSpeed(this.body, 0);
  1671. },
  1672. applyFocusForces(){
  1673. if(!this.isFocused()) {
  1674. this.pushAside()
  1675. }else{
  1676. this.bringToCenter()
  1677. }
  1678. },
  1679. isFocused(){
  1680. return this.map_mode === 'terraindevie'
  1681. || (this.map_mode === 'proximite' && this.concernement.has_proximites)
  1682. || (this.map_mode === 'superposition' && this.concernement.has_superpositions)
  1683. || (this.map_mode === 'action' && this.concernement.has_agissantes)
  1684. || (this.map_mode === 'puissancedagir' && this.concernement.has_puissancedagir)
  1685. || (this.map_mode === 'doleancer' && this.concernement.has_doleance);
  1686. },
  1687. pushAside(){
  1688. // console.log('pushAside');
  1689. // apply a force in direction of one side or an other depending of the start position
  1690. // the force is exponentialy proportional to the distance from the side
  1691. // INFO logarithmic force : https://stackoverflow.com/questions/846221/logarithmic-slider/846249#846249
  1692. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1693. let pseudo_center_x = this.opened_concernement
  1694. ? (this.canvas.width - this.cartouch_width) / 2
  1695. : this.canvas.width / 2;
  1696. // get the direction to the closest side
  1697. let dir = this.map_mode === 'superposition'
  1698. && this.concernement.superposition_constraints_id
  1699. && this.concernement.superposition_constraints_id[this.id]
  1700. && this.concernement.superposition_constraints_id[this.id].length // go to the right if has superposition constraint applied
  1701. ? 1 // to the right
  1702. : this.pos.x > pseudo_center_x // else
  1703. ? 1 // to the right
  1704. : -1; // to the left
  1705. // max and min item position
  1706. let minp = 0;
  1707. let maxp = dir < 0
  1708. ? pseudo_center_x
  1709. : this.canvas.width - pseudo_center_x;
  1710. // max and min force
  1711. let minf = 0;
  1712. let maxf = 6;
  1713. // scale factor
  1714. let scale = (maxf-minf) / (maxp-minp);
  1715. // get the inversed distance
  1716. let dist = dir < 0
  1717. ? this.pos.x
  1718. : this.canvas.width - this.pos.x; // get the distance from the side
  1719. // // calculate the force
  1720. // let x_force = Math.pow(dist/700,100) * dir;
  1721. // calculate the logarithmic force
  1722. let x_force = Math.exp(minf + scale*(dist-minp)) * dir;
  1723. let ori_pos = {x:pseudo_center_x, y:this.body.position.y};
  1724. Matter.Body.applyForce(
  1725. this.body,
  1726. ori_pos,
  1727. {
  1728. x: x_force,
  1729. y: 0
  1730. }
  1731. );
  1732. this.body.frictionAir = 0.01;
  1733. },
  1734. bringToCenter(){
  1735. // bring to the centre
  1736. // apply a force in direction of one side or an other depending of the start position
  1737. // the force is exponentialy inversed proportional to the distance from the side
  1738. // INFO logarithmic force : https://stackoverflow.com/questions/846221/logarithmic-slider/846249#846249
  1739. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1740. let pseudo_center_x = this.opened_concernement
  1741. ? (this.canvas.width - this.cartouch_width) / 2
  1742. : this.canvas.width / 2;
  1743. let dir = this.pos.x > pseudo_center_x
  1744. ? -1 // to left
  1745. : 1; // to right
  1746. // get the inversed distance from the side
  1747. let dist = dir < 0
  1748. ? this.pos.x - pseudo_center_x
  1749. : pseudo_center_x - this.pos.x;
  1750. if (dist > this.canvas.width/6) { // apply decreasing forces and increasing friction air only out of center to let the items float in the center zone
  1751. // max & min item position
  1752. let minp = 0;
  1753. let maxp = dir < 0
  1754. ? this.canvas.width - pseudo_center_x
  1755. : pseudo_center_x;
  1756. // X force decrsinsing near the center
  1757. // max and min force
  1758. let xminf = 0;
  1759. let xmaxf = 1 + Math.random()*4;
  1760. // scale factor
  1761. let xscale = (xmaxf-xminf) / (maxp-minp);
  1762. let x_force = Math.exp(xminf + xscale*(dist-minp)) * dir;
  1763. let ori_pos = dir < 0
  1764. ? {x:this.canvas.width, y:this.body.position.y}
  1765. : {x:0, y:this.body.position.y};
  1766. Matter.Body.applyForce(
  1767. this.body,
  1768. ori_pos,
  1769. {
  1770. x: x_force,
  1771. y: 0
  1772. }
  1773. );
  1774. // Friction air fa (increasing near the center)
  1775. let fa_minf = 0;
  1776. let fa_maxf = 6;
  1777. // scale factor
  1778. let fa_scale = (fa_maxf-fa_minf) / (maxp-minp);
  1779. let fa = Math.exp(fa_minf + fa_scale*(dist-minp)*-1);
  1780. this.body.frictionAir = fa;
  1781. // console.log(`bringToCenter dist:${dist}, x_force:${x_force}, friction air:${fa}`);
  1782. } else { // in the ceneter zone let items floats freely
  1783. let fa = 0.01;
  1784. let velocity = Matter.Body.getVelocity(this.body);
  1785. if (velocity.x) {
  1786. let velocityx = Math.abs(velocity.x);
  1787. // map a range of numbers to another range of numbers
  1788. // INFO https://stackoverflow.com/a/46462321
  1789. let velocity_range = [50, 1000];
  1790. let fa_range = [0,3];
  1791. fa = fa_range[0] + (velocityx - velocity_range[0]) * (fa_range[1] - fa_range[0]) / (velocity_range[1] - velocity_range[0]);
  1792. // console.log(`bringToCenter velocityx:${velocityx}, fa:${fa}, velocity`, velocity);
  1793. } else {
  1794. console.warn(`bringToCenter no velocity`, velocity);
  1795. }
  1796. this.body.frictionAir = fa;
  1797. }
  1798. },
  1799. applyShuffleForces() {
  1800. // console.log('applyShuffleForces');
  1801. // var dist, dir, x_velocity;
  1802. // dir = this.pos.x > this.canvas.width/2 ? -1 : 1; // get the direction to the centre
  1803. // dist = (dir < 0 ? this.pos.x - this.canvas.width/2 : this.canvas.width/2 - this.pos.x); // get the distance from the side
  1804. // x_velocity = Math.pow(dist/650,10) * dir;
  1805. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1806. let pseudo_center_x = this.opened_concernement
  1807. ? (this.canvas.width - this.cartouch_width) / 2
  1808. : this.canvas.width / 2;
  1809. // get the direction to the centre
  1810. let dir = this.pos.x > pseudo_center_x
  1811. ? -1 // to left
  1812. : 1; // to right
  1813. // get the inversed distance from the side
  1814. let dist = dir < 0
  1815. ? this.pos.x - pseudo_center_x
  1816. : pseudo_center_x - this.pos.x;
  1817. dist = dist > 1000 ? 1000 : dist;
  1818. if (dist > this.canvas.width/6) { // apply decreasing forces and increasing friction air only out of center to let the items float in the center zone
  1819. // max & min item position
  1820. let minp = 0;
  1821. let maxp = dir < 0
  1822. ? this.canvas.width - pseudo_center_x
  1823. : pseudo_center_x;
  1824. // X max and min force
  1825. let xminf = 0;
  1826. let xmaxf = 4 + Math.random()*3;
  1827. // scale factor
  1828. let xscale = (xmaxf-xminf) / (maxp-minp);
  1829. let x_velocity = Math.exp(xminf + xscale*(dist-minp))*dir;
  1830. // let y_velocity = 30 + Math.random() * 50;
  1831. // y_velocity = Math.random() > 0.5 ? -y_velocity : y_velocity;
  1832. // X max and min force
  1833. let yminf = 1;
  1834. let ymaxf = 2 + Math.random()*4;
  1835. // scale factor
  1836. let yscale = (ymaxf-yminf) / (maxp-minp);
  1837. let y_velocity = Math.exp(yminf + yscale*(dist-minp)) * (Math.random() > 0.5 ? 1 : -1); // let ori_pos = dir < 0
  1838. // ? {x:this.canvas.width, y:this.body.position.y}
  1839. // : {x:0, y:this.body.position.y};
  1840. // let x_force = Math.pow(dist/800,10) * dir;
  1841. console.log(`applyShuffleForces dir:${dir}, maxp:${maxp}, dist:${dist}, x_velocity:${x_velocity}, y_velocity:${y_velocity}`);
  1842. Matter.Body.setVelocity(this.body, {x: x_velocity, y: y_velocity});
  1843. } else { // if in center zone real shuffle velocity
  1844. // x_velocity = -50 + Math.random()*100;
  1845. // y_velocity = -50 + Math.random()*100;
  1846. // this.setInitBodyVelocity();
  1847. }
  1848. this.body.frictionAir = 0.01;
  1849. },
  1850. applyNormalForces () {
  1851. // bring gently to the centre
  1852. // apply a force in direction of one side or an other depending of the start position
  1853. // the force is exponentialy inversed proportional to the distance from the side
  1854. // INFO logarithmic force : https://stackoverflow.com/questions/846221/logarithmic-slider/846249#846249
  1855. // TODO cartouch width should change regarding actual cartouch is opened or not (and how many cartouch are opened)
  1856. // X
  1857. let pseudo_center_x = this.opened_concernement
  1858. ? (this.canvas.width - this.cartouch_width) / 2
  1859. : this.canvas.width / 2;
  1860. let xdir = this.pos.x > pseudo_center_x
  1861. ? -1 // to left
  1862. : 1; // to right
  1863. // get the inversed distance from the side
  1864. let xdist = xdir < 0
  1865. ? this.pos.x - pseudo_center_x
  1866. : pseudo_center_x - this.pos.x;
  1867. // Y
  1868. let pseudo_center_y = this.canvas.height / 2;
  1869. let ydir = this.pos.y > pseudo_center_y
  1870. ? -1 // to top
  1871. : 1; // to bottom
  1872. // get the inversed distance from the side
  1873. let ydist = ydir < 0
  1874. ? this.pos.y - pseudo_center_y
  1875. : pseudo_center_y - this.pos.y;
  1876. let k = 4;
  1877. if (xdist > this.canvas.width/k || ydist > this.canvas.height/k) { // apply decreasing forces and increasing friction air only out of center to let the items float in the center zone
  1878. // max and min force
  1879. let minf = 0;
  1880. let maxf = 0.1;
  1881. // X
  1882. // max & min item position
  1883. let xminp = 0;
  1884. let xmaxp = xdir < 0
  1885. ? this.canvas.width - pseudo_center_x
  1886. : pseudo_center_x;
  1887. // X force decrsinsing near the center
  1888. // scale factor
  1889. let xscale = (maxf-minf) / (xmaxp-xminp);
  1890. let x_force = Math.exp(minf + xscale*(xdist-xminp)) * xdir;
  1891. let xori_pos = xdir < 0
  1892. ? {x:this.canvas.width, y:this.body.position.y}
  1893. : {x:0, y:this.body.position.y};
  1894. Matter.Body.applyForce(
  1895. this.body,
  1896. xori_pos,
  1897. {
  1898. x: x_force,
  1899. y: 0
  1900. }
  1901. );
  1902. // Y
  1903. // max & min item position
  1904. let yminp = 0;
  1905. let ymaxp = ydir < 0
  1906. ? this.canvas.height - pseudo_center_y
  1907. : pseudo_center_y;
  1908. // X force decrsinsing near the center
  1909. // scale factor
  1910. let yscale = (maxf-minf) / (ymaxp-yminp);
  1911. let y_force = Math.exp(minf + yscale*(ydist-xminp)) * ydir;
  1912. let yori_pos = ydir < 0
  1913. ? {x:this.body.position.x, y:this.canvas.height}
  1914. : {x:this.body.position.x, y:0};
  1915. Matter.Body.applyForce(
  1916. this.body,
  1917. yori_pos,
  1918. {
  1919. x: 0,
  1920. y: y_force
  1921. }
  1922. );
  1923. // // Friction air fa (increasing near the center)
  1924. // let fa_minf = 0;
  1925. // let fa_maxf = 6;
  1926. // // scale factor
  1927. // let fa_scale = (fa_maxf-fa_minf) / (maxp-minp);
  1928. // let fa = Math.exp(fa_minf + fa_scale*(dist-minp)*-1);
  1929. // this.body.frictionAir = fa;
  1930. // console.log(`bringToCenter dist:${xdist}, x_force:${x_force}`);
  1931. } else { // in the ceneter zone let items floats freely
  1932. // let velocity = Matter.Body.getVelocity(this.body);
  1933. // let velocityx = Math.abs(velocity.x);
  1934. // // map a range of numbers to another range of numbers
  1935. // // INFO https://stackoverflow.com/a/46462321
  1936. // let velocity_range = [50, 1000];
  1937. // let fa_range = [0,3];
  1938. // let fa = fa_range[0] + (velocityx - velocity_range[0]) * (fa_range[1] - fa_range[0]) / (velocity_range[1] - velocity_range[0]);
  1939. // console.log(`bringToCenter velocity.x:${velocity.x}, fa:${fa}`);
  1940. // this.body.frictionAir = fa;
  1941. this.body.frictionAir = 0.1;
  1942. }
  1943. },
  1944. respawn() {
  1945. // respawn element if outside screen
  1946. if(this.pos.x <= 0
  1947. || this.pos.x >= this.canvas.width
  1948. || this.pos.y <= 0
  1949. || this.pos.y >= this.canvas.height){
  1950. this.pos = this.getRandomPos()
  1951. Matter.Body.setPosition(this.body, {x:this.pos.x, y:this.pos.y});
  1952. // this.setInitBodyVelocity();
  1953. Matter.Body.setVelocity(this.body, {x:0,y:0});
  1954. }
  1955. },
  1956. onAfterEngineUpdate (event) {
  1957. this.respawn();
  1958. this.paper_main_object.position = this.pos = this.body.position;
  1959. this.handlePaperVisibilityOnAfterEnginUpdate()
  1960. },
  1961. },
  1962. render() {
  1963. // console.log('render()', this.ctx);
  1964. },
  1965. }
  1966. </script>