escher.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = global || self, factory(global.Escher = {}));
  5. }(this, (function (exports) { 'use strict';
  6. /**
  7. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers (labeled x and y), which can be used to represent points in space, directions, etc.
  8. *
  9. * @class
  10. * @param {number} x
  11. * @param {number} y
  12. */
  13. function Vector2(x, y)
  14. {
  15. this.x = x || 0;
  16. this.y = y || 0;
  17. }
  18. /**
  19. * Set vector x and y values.
  20. *
  21. * @param {number} x
  22. * @param {number} y
  23. */
  24. Vector2.prototype.set = function(x, y)
  25. {
  26. this.x = x;
  27. this.y = y;
  28. };
  29. /**
  30. * Set a scalar value into the x and y values.
  31. */
  32. Vector2.prototype.setScalar = function(scalar)
  33. {
  34. this.x = scalar;
  35. this.y = scalar;
  36. };
  37. /**
  38. * Create a clone of this vector object.
  39. */
  40. Vector2.prototype.clone = function()
  41. {
  42. return new Vector2(this.x, this.y);
  43. };
  44. /**
  45. * Copy the content of another vector into this one.
  46. *
  47. * @param {Vector2} v
  48. */
  49. Vector2.prototype.copy = function(v)
  50. {
  51. this.x = v.x;
  52. this.y = v.y;
  53. };
  54. /**
  55. * Add the content of another vector to this one.
  56. *
  57. * @param {Vector2} v
  58. */
  59. Vector2.prototype.add = function(v)
  60. {
  61. this.x += v.x;
  62. this.y += v.y;
  63. };
  64. /**
  65. * Add a scalar value to booth vector components.
  66. *
  67. * @param {number} s
  68. */
  69. Vector2.prototype.addScalar = function(s)
  70. {
  71. this.x += s;
  72. this.y += s;
  73. };
  74. /**
  75. * Add two vectors and store the result in this vector.
  76. *
  77. * @param {Vector2} a
  78. * @param {Vector2} b
  79. */
  80. Vector2.prototype.addVectors = function(a, b)
  81. {
  82. this.x = a.x + b.x;
  83. this.y = a.y + b.y;
  84. };
  85. /**
  86. * Scale a vector components and add the result to this vector.
  87. *
  88. * @param {Vector2} v
  89. * @param {number} s
  90. */
  91. Vector2.prototype.addScaledVector = function(v, s)
  92. {
  93. this.x += v.x * s;
  94. this.y += v.y * s;
  95. };
  96. /**
  97. * Subtract the content of another vector to this one.
  98. *
  99. * @param {Vector2} v
  100. */
  101. Vector2.prototype.sub = function(v)
  102. {
  103. this.x -= v.x;
  104. this.y -= v.y;
  105. };
  106. /**
  107. * Subtract a scalar value to booth vector components.
  108. *
  109. * @param {number} s
  110. */
  111. Vector2.prototype.subScalar = function(s)
  112. {
  113. this.x -= s;
  114. this.y -= s;
  115. };
  116. /**
  117. * Subtract two vectors and store the result in this vector.
  118. *
  119. * @param {Vector2} a
  120. * @param {Vector2} b
  121. */
  122. Vector2.prototype.subVectors = function(a, b)
  123. {
  124. this.x = a.x - b.x;
  125. this.y = a.y - b.y;
  126. };
  127. /**
  128. * Multiply the content of another vector to this one.
  129. *
  130. * @param {Vector2} v
  131. */
  132. Vector2.prototype.multiply = function(v)
  133. {
  134. this.x *= v.x;
  135. this.y *= v.y;
  136. };
  137. /**
  138. * Multiply a scalar value by booth vector components.
  139. *
  140. * @param {number} scalar
  141. */
  142. Vector2.prototype.multiplyScalar = function(scalar)
  143. {
  144. this.x *= scalar;
  145. this.y *= scalar;
  146. };
  147. /**
  148. * Divide the content of another vector from this one.
  149. *
  150. * @param {Vector2} v
  151. */
  152. Vector2.prototype.divide = function(v)
  153. {
  154. this.x /= v.x;
  155. this.y /= v.y;
  156. };
  157. /**
  158. * Divide a scalar value by booth vector components.
  159. *
  160. * @param {number} s
  161. */
  162. Vector2.prototype.divideScalar = function(scalar)
  163. {
  164. return this.multiplyScalar(1 / scalar);
  165. };
  166. /**
  167. * Set the minimum of x and y coordinates between two vectors.
  168. *
  169. * X is set as the min between this vector and the other vector.
  170. *
  171. * @param {Vector2} v
  172. */
  173. Vector2.prototype.min = function(v)
  174. {
  175. this.x = Math.min(this.x, v.x);
  176. this.y = Math.min(this.y, v.y);
  177. };
  178. /**
  179. * Set the maximum of x and y coordinates between two vectors.
  180. *
  181. * X is set as the max between this vector and the other vector.
  182. *
  183. * @param {Vector2} v
  184. */
  185. Vector2.prototype.max = function(v)
  186. {
  187. this.x = Math.max(this.x, v.x);
  188. this.y = Math.max(this.y, v.y);
  189. };
  190. Vector2.prototype.clamp = function(min, max)
  191. {
  192. // assumes min < max, componentwise
  193. this.x = Math.max(min.x, Math.min(max.x, this.x));
  194. this.y = Math.max(min.y, Math.min(max.y, this.y));
  195. };
  196. Vector2.prototype.clampScalar = function(minVal, maxVal)
  197. {
  198. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  199. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  200. };
  201. Vector2.prototype.clampLength = function(min, max)
  202. {
  203. var length = this.length();
  204. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  205. };
  206. /**
  207. * Round the vector coordinates to integer by flooring to the smaller integer.
  208. */
  209. Vector2.prototype.floor = function()
  210. {
  211. this.x = Math.floor(this.x);
  212. this.y = Math.floor(this.y);
  213. };
  214. /**
  215. * Round the vector coordinates to integer by ceiling to the bigger integer.
  216. */
  217. Vector2.prototype.ceil = function()
  218. {
  219. this.x = Math.ceil(this.x);
  220. this.y = Math.ceil(this.y);
  221. };
  222. /**
  223. * Round the vector coordinates to their closest integer.
  224. */
  225. Vector2.prototype.round = function()
  226. {
  227. this.x = Math.round(this.x);
  228. this.y = Math.round(this.y);
  229. };
  230. /**
  231. * Negate the coordinates of this vector.
  232. */
  233. Vector2.prototype.negate = function()
  234. {
  235. this.x = -this.x;
  236. this.y = -this.y;
  237. return this;
  238. };
  239. /**
  240. * Dot multiplication between this vector and another vector.
  241. *
  242. * @param {Vector2} vector
  243. * @return {number} Result of the dot multiplication.
  244. */
  245. Vector2.prototype.dot = function(v)
  246. {
  247. return this.x * v.x + this.y * v.y;
  248. };
  249. /**
  250. * Cross multiplication between this vector and another vector.
  251. *
  252. * @param {Vector2} vector
  253. * @return {number} Result of the cross multiplication.
  254. */
  255. Vector2.prototype.cross = function(v)
  256. {
  257. return this.x * v.y - this.y * v.x;
  258. };
  259. /**
  260. * Squared length of the vector.
  261. *
  262. * Faster for comparions.
  263. */
  264. Vector2.prototype.lengthSq = function()
  265. {
  266. return this.x * this.x + this.y * this.y;
  267. };
  268. /**
  269. * Length of the vector.
  270. */
  271. Vector2.prototype.length = function()
  272. {
  273. return Math.sqrt(this.x * this.x + this.y * this.y);
  274. };
  275. /**
  276. * Manhattan length of the vector.
  277. */
  278. Vector2.prototype.manhattanLength = function()
  279. {
  280. return Math.abs(this.x) + Math.abs(this.y);
  281. };
  282. /**
  283. * Normalize the vector (make it length one).
  284. */
  285. Vector2.prototype.normalize = function()
  286. {
  287. return this.divideScalar(this.length() || 1);
  288. };
  289. /**
  290. * Computes the angle in radians with respect to the positive x-axis
  291. */
  292. Vector2.prototype.angle = function()
  293. {
  294. var angle = Math.atan2(this.y, this.x);
  295. if(angle < 0)
  296. {
  297. angle += 2 * Math.PI;
  298. }
  299. return angle;
  300. };
  301. /**
  302. * Distance between two vector positions.
  303. */
  304. Vector2.prototype.distanceTo = function(v)
  305. {
  306. return Math.sqrt(this.distanceToSquared(v));
  307. };
  308. /**
  309. * Distance between two vector positions squared.
  310. *
  311. * Faster for comparisons.
  312. */
  313. Vector2.prototype.distanceToSquared = function(v)
  314. {
  315. var dx = this.x - v.x;
  316. var dy = this.y - v.y;
  317. return dx * dx + dy * dy;
  318. };
  319. /**
  320. * Manhattan distance between two vector positions.
  321. */
  322. Vector2.prototype.manhattanDistanceTo = function(v)
  323. {
  324. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  325. };
  326. /**
  327. * Scale the vector to have a defined length value.
  328. */
  329. Vector2.prototype.setLength = function(length)
  330. {
  331. return this.normalize().multiplyScalar(length);
  332. };
  333. Vector2.prototype.lerp = function(v, alpha)
  334. {
  335. this.x += (v.x - this.x) * alpha;
  336. this.y += (v.y - this.y) * alpha;
  337. };
  338. Vector2.prototype.lerpVectors = function(v1, v2, alpha)
  339. {
  340. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  341. };
  342. /**
  343. * Check if two vectors are equal.
  344. *
  345. * @param {Vector2} v
  346. */
  347. Vector2.prototype.equals = function(v)
  348. {
  349. return ((v.x === this.x) && (v.y === this.y));
  350. };
  351. /**
  352. * Set vector value from array with a offset.
  353. *
  354. * @param {array} array
  355. * @param {number} [offset]
  356. */
  357. Vector2.prototype.fromArray = function(array, offset)
  358. {
  359. if(offset === undefined) offset = 0;
  360. this.x = array[offset];
  361. this.y = array[offset + 1];
  362. };
  363. /**
  364. * Convert this vector to an array.
  365. *
  366. * @param {array} array
  367. * @param {number} [offset]
  368. */
  369. Vector2.prototype.toArray = function(array, offset)
  370. {
  371. if(array === undefined) array = [];
  372. if(offset === undefined) offset = 0;
  373. array[offset] = this.x;
  374. array[offset + 1] = this.y;
  375. return array;
  376. };
  377. /**
  378. * Rotate the vector around a central point.
  379. *
  380. * @param {Vector2} center
  381. * @param {number} angle
  382. */
  383. Vector2.prototype.rotateAround = function(center, angle)
  384. {
  385. var c = Math.cos(angle);
  386. var s = Math.sin(angle);
  387. var x = this.x - center.x;
  388. var y = this.y - center.y;
  389. this.x = x * c - y * s + center.x;
  390. this.y = x * s + y * c + center.y;
  391. };
  392. /**
  393. * 2D 3x2 transformation matrix, used to represent linear geometric transformations over objects.
  394. *
  395. * The values of the matrix are stored in a numeric array and can be applied to the canvas or DOM elements.
  396. *
  397. * @class
  398. * @param {number[]} values Array of matrix values by row, needs to have exactly 6 values.
  399. */
  400. function Matrix(values)
  401. {
  402. if(values !== undefined)
  403. {
  404. this.m = values;
  405. }
  406. else
  407. {
  408. this.identity();
  409. }
  410. }
  411. /**
  412. * Copy the content of another matrix and store in this one.
  413. *
  414. * @param {Matrix} mat Matrix to copy values from.
  415. */
  416. Matrix.prototype.copy = function(mat)
  417. {
  418. this.m = mat.m.slice(0);
  419. };
  420. /**
  421. * Create a new matrix object with a copy of the content of this one.
  422. *
  423. * @return {Matrix} Copy of this matrix.
  424. */
  425. Matrix.prototype.clone = function()
  426. {
  427. return new Matrix(this.m.slice(0))
  428. };
  429. /**
  430. * Reset this matrix to identity.
  431. */
  432. Matrix.prototype.identity = function()
  433. {
  434. this.m = [1, 0, 0, 1, 0, 0];
  435. };
  436. /**
  437. * Multiply another matrix by this one and store the result.
  438. *
  439. * @param {Matrix} mat
  440. */
  441. Matrix.prototype.multiply = function(mat)
  442. {
  443. var m0 = this.m[0] * mat.m[0] + this.m[2] * mat.m[1];
  444. var m1 = this.m[1] * mat.m[0] + this.m[3] * mat.m[1];
  445. var m2 = this.m[0] * mat.m[2] + this.m[2] * mat.m[3];
  446. var m3 = this.m[1] * mat.m[2] + this.m[3] * mat.m[3];
  447. var m4 = this.m[0] * mat.m[4] + this.m[2] * mat.m[5] + this.m[4];
  448. var m5 = this.m[1] * mat.m[4] + this.m[3] * mat.m[5] + this.m[5];
  449. this.m = [m0, m1, m2, m3, m4, m5];
  450. };
  451. /**
  452. * Premultiply another matrix by this one and store the result.
  453. *
  454. * @param {Matrix} mat
  455. */
  456. Matrix.prototype.premultiply = function(mat)
  457. {
  458. var m0 = mat.m[0] * this.m[0] + mat.m[2] * this.m[1];
  459. var m1 = mat.m[1] * this.m[0] + mat.m[3] * this.m[1];
  460. var m2 = mat.m[0] * this.m[2] + mat.m[2] * this.m[3];
  461. var m3 = mat.m[1] * this.m[2] + mat.m[3] * this.m[3];
  462. var m4 = mat.m[0] * this.m[4] + mat.m[2] * this.m[5] + mat.m[4];
  463. var m5 = mat.m[1] * this.m[4] + mat.m[3] * this.m[5] + mat.m[5];
  464. this.m = [m0, m1, m2, m3, m4, m5];
  465. };
  466. /**
  467. * Compose this transformation matrix with position scale and rotation and origin point.
  468. *
  469. * @param {number} px Position X
  470. * @param {number} py Position Y
  471. * @param {number} sx Scale X
  472. * @param {number} sy Scale Y
  473. * @param {number} ox Origin X (applied before scale and rotation)
  474. * @param {number} oy Origin Y (applied before scale and rotation)
  475. * @param {number} a Rotation angle (radians).
  476. */
  477. Matrix.prototype.compose = function(px, py, sx, sy, ox, oy, a)
  478. {
  479. this.m = [1, 0, 0, 1, px, py];
  480. if(a !== 0)
  481. {
  482. var c = Math.cos(a);
  483. var s = Math.sin(a);
  484. this.multiply(new Matrix([c, s, -s, c, 0, 0]));
  485. }
  486. if(sx !== 1 || sy !== 1)
  487. {
  488. this.scale(sx, sy);
  489. }
  490. if(ox !== 0 || oy !== 0)
  491. {
  492. this.multiply(new Matrix([1, 0, 0, 1, -ox, -oy]));
  493. }
  494. };
  495. /**
  496. * Apply translation to this matrix.
  497. *
  498. * Adds position over the transformation already stored in the matrix.
  499. *
  500. * @param {number} x
  501. * @param {number} y
  502. */
  503. Matrix.prototype.translate = function(x, y)
  504. {
  505. this.m[4] += this.m[0] * x + this.m[2] * y;
  506. this.m[5] += this.m[1] * x + this.m[3] * y;
  507. };
  508. /**
  509. * Apply rotation to this matrix.
  510. *
  511. * @param {number} rad Angle to rotate the matrix in radians.
  512. */
  513. Matrix.prototype.rotate = function(rad)
  514. {
  515. var c = Math.cos(rad);
  516. var s = Math.sin(rad);
  517. var m11 = this.m[0] * c + this.m[2] * s;
  518. var m12 = this.m[1] * c + this.m[3] * s;
  519. var m21 = this.m[0] * -s + this.m[2] * c;
  520. var m22 = this.m[1] * -s + this.m[3] * c;
  521. this.m[0] = m11;
  522. this.m[1] = m12;
  523. this.m[2] = m21;
  524. this.m[3] = m22;
  525. };
  526. /**
  527. * Apply scale to this matrix.
  528. *
  529. * @param {number} sx
  530. * @param {number} sy
  531. */
  532. Matrix.prototype.scale = function(sx, sy)
  533. {
  534. this.m[0] *= sx;
  535. this.m[1] *= sx;
  536. this.m[2] *= sy;
  537. this.m[3] *= sy;
  538. };
  539. /**
  540. * Set the position of the transformation matrix.
  541. *
  542. * @param {number} x
  543. * @param {number} y
  544. */
  545. Matrix.prototype.setPosition = function(x, y)
  546. {
  547. this.m[4] = x;
  548. this.m[5] = y;
  549. };
  550. /**
  551. * Extract the scale from the transformation matrix.
  552. *
  553. * @return {Vector2} Scale of the matrix transformation.
  554. */
  555. Matrix.prototype.getScale = function()
  556. {
  557. return new Vector2(this.m[0], this.m[3]);
  558. };
  559. /**
  560. * Extract the position from the transformation matrix.
  561. *
  562. * @return {Vector2} Position of the matrix transformation.
  563. */
  564. Matrix.prototype.getPosition = function()
  565. {
  566. return new Vector2(this.m[4], this.m[5]);
  567. };
  568. /**
  569. * Apply skew to this matrix.
  570. */
  571. Matrix.prototype.skew = function(radianX, radianY)
  572. {
  573. this.multiply(new Matrix([1, Math.tan(radianY), Math.tan(radianX), 1, 0, 0]));
  574. };
  575. /**
  576. * Get the matrix determinant.
  577. *
  578. * @return {number} Determinant of this matrix.
  579. */
  580. Matrix.prototype.determinant = function()
  581. {
  582. return 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]);
  583. };
  584. /**
  585. * Get the inverse matrix.
  586. *
  587. * @return {Matrix} New matrix instance containing the inverse matrix.
  588. */
  589. Matrix.prototype.getInverse = function()
  590. {
  591. var d = this.determinant();
  592. return new Matrix([this.m[3] * d, -this.m[1] * d, -this.m[2] * d, this.m[0] * d, d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]), d * (this.m[1] * this.m[4] - this.m[0] * this.m[5])]);
  593. };
  594. /**
  595. * Transform a point using this matrix.
  596. *
  597. * @param {Vector2} p Point to be transformed.
  598. * @return {Vector2} Transformed point.
  599. */
  600. Matrix.prototype.transformPoint = function(p)
  601. {
  602. var px = p.x * this.m[0] + p.y * this.m[2] + this.m[4];
  603. var py = p.x * this.m[1] + p.y * this.m[3] + this.m[5];
  604. return new Vector2(px, py);
  605. };
  606. /**
  607. * Set a canvas context to use this transformation.
  608. *
  609. * @param {CanvasRenderingContext2D} context Canvas context to apply this matrix transform.
  610. */
  611. Matrix.prototype.setContextTransform = function(context)
  612. {
  613. context.setTransform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  614. };
  615. /**
  616. * Transform on top of the current context transformation.
  617. *
  618. * @param {CanvasRenderingContext2D} context Canvas context to apply this matrix transform.
  619. */
  620. Matrix.prototype.tranformContext = function(context)
  621. {
  622. context.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
  623. };
  624. /**
  625. * Generate a CSS transform string that can be applied to the transform style of any DOM element.
  626. *
  627. * @returns {string} CSS transform matrix.
  628. */
  629. Matrix.prototype.cssTransform = function()
  630. {
  631. return "matrix(" + this.m[0] + "," + this.m[1] + "," + this.m[2] + "," + this.m[3] + "," + this.m[4] + "," + this.m[5] + ")";
  632. };
  633. /**
  634. * Class to implement UUID generation methods.
  635. *
  636. * @class
  637. */
  638. function UUID(){}
  639. /**
  640. * Generates a new random UUID v4 as string.
  641. *
  642. * @static
  643. * @return {string} UUID generated as string.
  644. */
  645. UUID.generate = (function ()
  646. {
  647. var lut = [];
  648. for(var i = 0; i < 256; i++)
  649. {
  650. lut[i] = (i < 16 ? "0" : "") + (i).toString(16);
  651. }
  652. return function generateUUID()
  653. {
  654. var d0 = Math.random() * 0XFFFFFFFF | 0;
  655. var d1 = Math.random() * 0XFFFFFFFF | 0;
  656. var d2 = Math.random() * 0XFFFFFFFF | 0;
  657. var d3 = Math.random() * 0XFFFFFFFF | 0;
  658. var uuid = lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + "-" +
  659. lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + "-" + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + "-" +
  660. lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + "-" + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
  661. lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
  662. return uuid.toUpperCase();
  663. };
  664. })();
  665. /**
  666. * Base object class, implements all the object positioning and scaling features.
  667. *
  668. * Stores all the base properties shared between all objects as the position, transformation properties, children etc.
  669. *
  670. * Object2D object can be used as a group to the other objects drawn.
  671. *
  672. * @class
  673. */
  674. function Object2D()
  675. {
  676. /**
  677. * UUID of the object.
  678. *
  679. * @type {string}
  680. */
  681. this.uuid = UUID.generate();
  682. /**
  683. * List of children objects attached to the object.
  684. *
  685. * @type {Object2D[]}
  686. */
  687. this.children = [];
  688. /**
  689. * Parent object, the object position is affected by its parent position.
  690. *
  691. * @type {Object2D}
  692. */
  693. this.parent = null;
  694. /**
  695. * Depth level in the object tree, objects with higher depth are drawn on top.
  696. *
  697. * The layer value is considered first.
  698. *
  699. * @type {number}
  700. */
  701. this.level = 0;
  702. /**
  703. * Position of the object.
  704. *
  705. * The world position of the object is affected by its parent transform.
  706. *
  707. * @type {Vector2}
  708. */
  709. this.position = new Vector2(0, 0);
  710. /**
  711. * Origin of the object used as point of rotation.
  712. *
  713. * @type {Vector2}
  714. */
  715. this.origin = new Vector2(0, 0);
  716. /**
  717. * Scale of the object.
  718. *
  719. * The world scale of the object is affected by the parent transform.
  720. *
  721. * @type {Vector2}
  722. */
  723. this.scale = new Vector2(1, 1);
  724. /**
  725. * Rotation of the object relative to its center.
  726. *
  727. * The world rotation of the object is affected by the parent transform.
  728. *
  729. * @type {number}
  730. */
  731. this.rotation = 0.0;
  732. /**
  733. * Indicates if the object is visible.
  734. *
  735. * @type {boolean}
  736. */
  737. this.visible = true;
  738. /**
  739. * Layer of this object, objects are sorted by layer value.
  740. *
  741. * Lower layer value is draw first, higher layer value is drawn on top.
  742. *
  743. * @type {number}
  744. */
  745. this.layer = 0;
  746. /**
  747. * Local transformation matrix applied to the object.
  748. *
  749. * @type {Matrix}
  750. */
  751. this.matrix = new Matrix();
  752. /**
  753. * Global transformation matrix multiplied by the parent matrix.
  754. *
  755. * Used to transform the object before projecting into screen coordinates.
  756. *
  757. * @type {Matrix}
  758. */
  759. this.globalMatrix = new Matrix();
  760. /**
  761. * Inverse of the global matrix.
  762. *
  763. * Used to convert pointer input points into object coordinates.
  764. *
  765. * @type {Matrix}
  766. */
  767. this.inverseGlobalMatrix = new Matrix();
  768. /**
  769. * Mask objects being applied to this object. Used to mask/subtract portions of this object when rendering.
  770. *
  771. * Multiple masks can be used simultaneously. Same mask might be reused for multiple objects.
  772. *
  773. * @type {Mask[]}
  774. */
  775. this.masks = [];
  776. /**
  777. * Indicates if the transform matrix should be automatically updated every frame.
  778. *
  779. * Set this false for better performance. But if you do so dont forget to set matrixNeedsUpdate every time that a transform attribute is changed.
  780. *
  781. * @type {boolean}
  782. */
  783. this.matrixAutoUpdate = true;
  784. /**
  785. * Indicates if the matrix needs to be updated, should be set true after changes to the object position, scale or rotation.
  786. *
  787. * The matrix is updated before rendering the object, after the matrix is updated this attribute is automatically reset to false.
  788. *
  789. * @type {boolean}
  790. */
  791. this.matrixNeedsUpdate = true;
  792. /**
  793. * Draggable controls if its possible to drag the object around. Set this true to enable dragging events on this object.
  794. *
  795. * The onPointerDrag callback is used to update the state of the object while being dragged, by default it just updates the object position.
  796. *
  797. * @type {boolean}
  798. */
  799. this.draggable = false;
  800. /**
  801. * Indicates if this object uses pointer events.
  802. *
  803. * Can be set false to skip the pointer interaction events, better performance if pointer events are not required.
  804. *
  805. * @type {boolean}
  806. */
  807. this.pointerEvents = true;
  808. /**
  809. * Flag to indicate whether this object ignores the viewport transformation.
  810. *
  811. * @type {boolean}
  812. */
  813. this.ignoreViewport = false;
  814. /**
  815. * Flag to indicate if the context of canvas should be saved before render.
  816. *
  817. * @type {boolean}
  818. */
  819. this.saveContextState = true;
  820. /**
  821. * Flag to indicate if the context of canvas should be restored after render.
  822. *
  823. * @type {boolean}
  824. */
  825. this.restoreContextState = true;
  826. /**
  827. * Flag indicating if the pointer is inside of the element.
  828. *
  829. * Used to control object event.
  830. *
  831. * @type {boolean}
  832. */
  833. this.pointerInside = false;
  834. /**
  835. * Flag to indicate if the object is currently being dragged.
  836. *
  837. * @type {boolean}
  838. */
  839. this.beingDragged = false;
  840. }
  841. /**
  842. * Traverse the object tree and run a function for all objects.
  843. *
  844. * @param {Function} callback Callback function that receives the object as parameter.
  845. */
  846. Object2D.prototype.traverse = function(callback)
  847. {
  848. callback(this);
  849. var children = this.children;
  850. for(var i = 0; i < children.length; i++)
  851. {
  852. children[i].traverse(callback);
  853. }
  854. };
  855. /**
  856. * Get a object from its children list by its UUID.
  857. *
  858. * @param {string} uuid UUID of the object to get.
  859. * @return {Object2D} The object that has the UUID specified, null if the object was not found.
  860. */
  861. Object2D.prototype.getChildByUUID = function(uuid)
  862. {
  863. var object = null;
  864. this.traverse(function(child)
  865. {
  866. if(child.uuid === uuid)
  867. {
  868. object = child;
  869. }
  870. });
  871. return object;
  872. };
  873. /**
  874. * Attach a children to this object.
  875. *
  876. * The object is set as children of this object and the transformations applied to this object are traversed to its children.
  877. *
  878. * @param {Object2D} object Object to attach to this object.
  879. */
  880. Object2D.prototype.add = function(object)
  881. {
  882. object.parent = this;
  883. object.level = this.level + 1;
  884. object.traverse(function(child)
  885. {
  886. if(child.onAdd !== null)
  887. {
  888. child.onAdd(this);
  889. }
  890. });
  891. this.children.push(object);
  892. };
  893. /**
  894. * Remove object from the children list.
  895. *
  896. * @param {Object2D} children Object to be removed.
  897. */
  898. Object2D.prototype.remove = function(children)
  899. {
  900. var index = this.children.indexOf(children);
  901. if(index !== -1)
  902. {
  903. var object = this.children[index];
  904. object.parent = null;
  905. object.level = 0;
  906. object.traverse(function(child)
  907. {
  908. if(child.onRemove !== null)
  909. {
  910. child.onRemove(this);
  911. }
  912. });
  913. this.children.splice(index, 1);
  914. }
  915. };
  916. /**
  917. * Check if a point is inside of the object.
  918. *
  919. * Used to update the point events attached to the object.
  920. *
  921. * @return {boolean} True if the point is inside of the object.
  922. */
  923. Object2D.prototype.isInside = function(point)
  924. {
  925. return false;
  926. };
  927. /**
  928. * Update the transformation matrix of the object.
  929. *
  930. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  931. */
  932. Object2D.prototype.updateMatrix = function(context)
  933. {
  934. if(this.matrixAutoUpdate || this.matrixNeedsUpdate)
  935. {
  936. this.matrix.compose(this.position.x, this.position.y, this.scale.x, this.scale.y, this.origin.x, this.origin.y, this.rotation);
  937. this.globalMatrix.copy(this.matrix);
  938. if(this.parent !== null)
  939. {
  940. this.globalMatrix.premultiply(this.parent.globalMatrix);
  941. }
  942. this.inverseGlobalMatrix = this.globalMatrix.getInverse();
  943. this.matrixNeedsUpdate = false;
  944. }
  945. };
  946. /**
  947. * Apply the transform to the rendering context, it is assumed that the viewport transform is pre-applied to the context.
  948. *
  949. * This is called before style() and draw(). It can also be used for some pre-rendering logic.
  950. *
  951. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  952. * @param {Viewport} viewport Viewport applied to the canvas.
  953. */
  954. Object2D.prototype.transform = function(context, viewport)
  955. {
  956. this.globalMatrix.tranformContext(context);
  957. };
  958. /**
  959. * Style is called right before draw() it should not draw any content into the canvas, all context styling should be applied here (colors, fonts, etc).
  960. *
  961. * The draw() and style() methods can be useful for objects that share the same styling attributes but are drawing differently.
  962. *
  963. * Should be implemented by underlying classes.
  964. *
  965. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  966. * @param {Viewport} viewport Viewport used to view the canvas content.
  967. * @param {DOM} canvas DOM canvas element where the content is being drawn.
  968. */
  969. Object2D.prototype.style = null; // function(context, viewport, canvas){};
  970. /**
  971. * Draw the object into the canvas, this is called transform() and style(), should be where the content is actually drawn into the canvas.
  972. *
  973. * Should be implemented by underlying classes.
  974. *
  975. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  976. * @param {Viewport} viewport Viewport used to view the canvas content.
  977. * @param {DOM} canvas DOM canvas element where the content is being drawn.
  978. */
  979. Object2D.prototype.draw = null; // function(context, viewport, canvas){};
  980. /**
  981. * Callback method while the object is being dragged across the screen.
  982. *
  983. * By default is adds the delta value to the object position (making it follow the mouse movement).
  984. *
  985. * Delta is the movement of the pointer already translated into local object coordinates.
  986. *
  987. * Receives (pointer, viewport, delta) as arguments.
  988. *
  989. * @param {Pointer} pointer Pointer object that receives the user input.
  990. * @param {Viewport} viewport Viewport where the object is drawn.
  991. * @param {Vector2} delta Pointer movement in world space.
  992. */
  993. Object2D.prototype.onPointerDrag = function(pointer, viewport, delta)
  994. {
  995. this.position.add(delta);
  996. };
  997. /**
  998. * Method called when the object its added to a parent.
  999. *
  1000. * @param {Object2D} parent Parent object were it was added.
  1001. */
  1002. Object2D.prototype.onAdd = null;
  1003. /**
  1004. * Method called when the object gets removed from its parent
  1005. *
  1006. * @param {Object2D} parent Parent object from were the object is being removed.
  1007. */
  1008. Object2D.prototype.onRemove = null;
  1009. /**
  1010. * Callback method called every time before the object is draw into the canvas.
  1011. *
  1012. * Can be used to run preparation code, move the object, etc.
  1013. */
  1014. Object2D.prototype.onUpdate = null;
  1015. /**
  1016. * Callback method called when the pointer enters the object.
  1017. *
  1018. * Receives (pointer, viewport) as arguments.
  1019. *
  1020. * @param {Pointer} pointer Pointer object that receives the user input.
  1021. * @param {Viewport} viewport Viewport where the object is drawn.
  1022. */
  1023. Object2D.prototype.onPointerEnter = null;
  1024. /**
  1025. * Callback method called when the was inside of the object and leaves the object.
  1026. *
  1027. * Receives (pointer, viewport) as arguments.
  1028. *
  1029. * @param {Pointer} pointer Pointer object that receives the user input.
  1030. * @param {Viewport} viewport Viewport where the object is drawn.
  1031. */
  1032. Object2D.prototype.onPointerLeave = null;
  1033. /**
  1034. * Callback method while the pointer is over (inside) of the object.
  1035. *
  1036. * Receives (pointer, viewport) as arguments.
  1037. *
  1038. * @param {Pointer} pointer Pointer object that receives the user input.
  1039. * @param {Viewport} viewport Viewport where the object is drawn.
  1040. */
  1041. Object2D.prototype.onPointerOver = null;
  1042. /**
  1043. * Callback method called while the pointer button is pressed.
  1044. *
  1045. * Receives (pointer, viewport) as arguments.
  1046. *
  1047. * @param {Pointer} pointer Pointer object that receives the user input.
  1048. * @param {Viewport} viewport Viewport where the object is drawn.
  1049. */
  1050. Object2D.prototype.onButtonPressed = null;
  1051. /**
  1052. * Callback method called while the pointer button is double clicked.
  1053. *
  1054. * Receives (pointer, viewport) as arguments.
  1055. *
  1056. * @param {Pointer} pointer Pointer object that receives the user input.
  1057. * @param {Viewport} viewport Viewport where the object is drawn.
  1058. */
  1059. Object2D.prototype.onDoubleClick = null;
  1060. /**
  1061. * Callback method called when the pointer button is pressed down (single time).
  1062. *
  1063. * Receives (pointer, viewport) as arguments.
  1064. *
  1065. * @param {Pointer} pointer Pointer object that receives the user input.
  1066. * @param {Viewport} viewport Viewport where the object is drawn.
  1067. */
  1068. Object2D.prototype.onButtonDown = null;
  1069. /**
  1070. * Callback method called when the pointer button is released (single time).
  1071. *
  1072. * Receives (pointer, viewport) as arguments.
  1073. *
  1074. * @param {Pointer} pointer Pointer object that receives the user input.
  1075. * @param {Viewport} viewport Viewport where the object is drawn.
  1076. */
  1077. Object2D.prototype.onButtonUp = null;
  1078. /**
  1079. * Text element, used to draw text into the canvas.
  1080. *
  1081. * @class
  1082. * @extends {Object2D}
  1083. */
  1084. function Text()
  1085. {
  1086. Object2D.call(this);
  1087. /**
  1088. * Text value.
  1089. */
  1090. this.text = "";
  1091. /**
  1092. * Font of the text.
  1093. */
  1094. this.font = "16px Arial";
  1095. /**
  1096. * Style of the object border line.
  1097. *
  1098. * If set null it is ignored.
  1099. */
  1100. this.strokeStyle = null;
  1101. /**
  1102. * Line width, only used if a valid strokeStyle is defined.
  1103. */
  1104. this.lineWidth = 1;
  1105. /**
  1106. * Background color of the box.
  1107. *
  1108. * If set null it is ignored.
  1109. */
  1110. this.fillStyle = "#000000";
  1111. /**
  1112. * Text align property.
  1113. */
  1114. this.textAlign = "center";
  1115. }
  1116. Text.prototype = Object.create(Object2D.prototype);
  1117. Text.prototype.draw = function(context, viewport, canvas)
  1118. {
  1119. context.font = this.font;
  1120. context.textAlign = this.textAlign;
  1121. context.textBaseline = "middle";
  1122. if(this.fillStyle !== null)
  1123. {
  1124. context.fillStyle = this.fillStyle;
  1125. context.fillText(this.text, 0, 0);
  1126. }
  1127. if(this.strokeStyle !== null)
  1128. {
  1129. context.strokeStyle = this.strokeStyle;
  1130. context.strokeText(this.text, 0, 0);
  1131. }
  1132. };
  1133. /**
  1134. * Multiple line text drawing directly into the canvas.
  1135. *
  1136. * Has support for basic text indent and alignment.
  1137. *
  1138. * @class
  1139. * @extends {Text}
  1140. */
  1141. function MultiLineText()
  1142. {
  1143. Text.call(this);
  1144. /**
  1145. * Text baseline defines the vertical position of the text relative to the imaginary line Y position.
  1146. *
  1147. * @type {string}
  1148. */
  1149. this.textBaseline = "middle";
  1150. /**
  1151. * Maximum width of the text content. After text reaches the max width a line break is placed.
  1152. *
  1153. * Can be set to null to be ignored.
  1154. *
  1155. * @type {number}
  1156. */
  1157. this.maxWidth = null;
  1158. /**
  1159. * Height of each line of text, can be smaller or larger than the actual font size.
  1160. *
  1161. * Can be set to null to be ignored.
  1162. *
  1163. * @type {number}
  1164. */
  1165. this.lineHeight = null;
  1166. }
  1167. MultiLineText.prototype = Object.create(Text.prototype);
  1168. MultiLineText.prototype.draw = function(context, viewport, canvas)
  1169. {
  1170. context.font = this.font;
  1171. context.textAlign = this.textAlign;
  1172. context.textBaseline = this.textBaseline;
  1173. var lineHeight = this.lineHeight || Number.parseFloat(this.font);
  1174. var lines = this.text.split("\n");
  1175. var offsetY = 0;
  1176. // Iterate trough all lines (breakpoints)
  1177. for(var i = 0; i < lines.length; i++)
  1178. {
  1179. var line = lines[i];
  1180. var size = context.measureText(line);
  1181. var sublines = [];
  1182. // Split into multiple sub-lines
  1183. if(this.maxWidth !== null && size.width > this.maxWidth)
  1184. {
  1185. while(line.length > 0)
  1186. {
  1187. var subline = "";
  1188. var subsize = context.measureText(subline + line[0]);
  1189. while(subsize.width < this.maxWidth && line.length > 0)
  1190. {
  1191. subline += line[0];
  1192. line = line.substr(1);
  1193. subsize = context.measureText(subline + line[0]);
  1194. }
  1195. sublines.push(subline);
  1196. }
  1197. }
  1198. // Fits into a single line
  1199. else
  1200. {
  1201. sublines = [line];
  1202. }
  1203. for(var j = 0; j < sublines.length; j++)
  1204. {
  1205. if(this.fillStyle !== null)
  1206. {
  1207. context.fillStyle = this.fillStyle;
  1208. context.fillText(sublines[j], this.position.x, this.position.y + offsetY);
  1209. }
  1210. if(this.strokeStyle !== null)
  1211. {
  1212. context.strokeStyle = this.strokeStyle;
  1213. context.strokeText(sublines[j], this.position.x, this.position.y + offsetY);
  1214. }
  1215. offsetY += lineHeight;
  1216. }
  1217. }
  1218. };
  1219. /**
  1220. * EventManager is used to manager DOM events creating and destruction in a single function call.
  1221. *
  1222. * It is used by objects to make it easier to add and remove events from global DOM objects.
  1223. *
  1224. * @class
  1225. */
  1226. function EventManager()
  1227. {
  1228. /**
  1229. * Stores all events in the manager, their target and callback.
  1230. *
  1231. * Format [target, event, callback, active]
  1232. *
  1233. * @type {Array}
  1234. */
  1235. this.events = [];
  1236. }
  1237. /**
  1238. * Add new event to the manager.
  1239. *
  1240. * @param {Element} target Event target element.
  1241. * @param {String} event Event name.
  1242. * @param {Function} callback Callback function.
  1243. */
  1244. EventManager.prototype.add = function(target, event, callback)
  1245. {
  1246. this.events.push([target, event, callback, false]);
  1247. };
  1248. /**
  1249. * Destroys this manager and remove all events.
  1250. */
  1251. EventManager.prototype.clear = function()
  1252. {
  1253. this.destroy();
  1254. this.events = [];
  1255. };
  1256. /**
  1257. * Creates all events in this manager.
  1258. */
  1259. EventManager.prototype.create = function()
  1260. {
  1261. for(var i = 0; i < this.events.length; i++)
  1262. {
  1263. var event = this.events[i];
  1264. event[0].addEventListener(event[1], event[2]);
  1265. event[3] = true;
  1266. }
  1267. };
  1268. /**
  1269. * Removes all events in this manager.
  1270. */
  1271. EventManager.prototype.destroy = function()
  1272. {
  1273. for(var i = 0; i < this.events.length; i++)
  1274. {
  1275. var event = this.events[i];
  1276. event[0].removeEventListener(event[1], event[2]);
  1277. event[3] = false;
  1278. }
  1279. };
  1280. /**
  1281. * Key is used by Keyboard, Pointer, etc, to represent a key state.
  1282. *
  1283. * @class
  1284. */
  1285. function Key()
  1286. {
  1287. /**
  1288. * Indicates if this key is currently pressed.
  1289. */
  1290. this.pressed = false;
  1291. /**
  1292. * Indicates if this key was just pressed.
  1293. */
  1294. this.justPressed = false;
  1295. /**
  1296. * Indicates if this key was just released.
  1297. */
  1298. this.justReleased = false;
  1299. }
  1300. Key.DOWN = -1;
  1301. Key.UP = 1;
  1302. Key.RESET = 0;
  1303. Key.prototype.constructor = Key;
  1304. /**
  1305. * Update Key status based on new key state.
  1306. */
  1307. Key.prototype.update = function(action)
  1308. {
  1309. this.justPressed = false;
  1310. this.justReleased = false;
  1311. if(action === Key.DOWN)
  1312. {
  1313. if(this.pressed === false)
  1314. {
  1315. this.justPressed = true;
  1316. }
  1317. this.pressed = true;
  1318. }
  1319. else if(action === Key.UP)
  1320. {
  1321. if(this.pressed)
  1322. {
  1323. this.justReleased = true;
  1324. }
  1325. this.pressed = false;
  1326. }
  1327. else if(action === Key.RESET)
  1328. {
  1329. this.justReleased = false;
  1330. this.justPressed = false;
  1331. }
  1332. };
  1333. /**
  1334. * Set this key attributes manually.
  1335. */
  1336. Key.prototype.set = function(justPressed, pressed, justReleased)
  1337. {
  1338. this.justPressed = justPressed;
  1339. this.pressed = pressed;
  1340. this.justReleased = justReleased;
  1341. };
  1342. /**
  1343. * Reset key to default values.
  1344. */
  1345. Key.prototype.reset = function()
  1346. {
  1347. this.justPressed = false;
  1348. this.pressed = false;
  1349. this.justReleased = false;
  1350. };
  1351. /**
  1352. * Pointer object is used to called input from the user, works for booth mouse or touch screens.
  1353. *
  1354. * It is responsible for synchronizing user input with the render of the graphics.
  1355. *
  1356. * @class
  1357. * @param {Element} domElement DOM element to create the pointer events.
  1358. * @param {Element} canvas Canvas DOM element where the content is being drawn.
  1359. */
  1360. function Pointer(domElement, canvas)
  1361. {
  1362. //Raw data
  1363. this._keys = new Array(5);
  1364. this._position = new Vector2(0, 0);
  1365. this._positionUpdated = false;
  1366. this._delta = new Vector2(0, 0);
  1367. this._wheel = 0;
  1368. this._wheelUpdated = false;
  1369. this._doubleClicked = new Array(5);
  1370. /**
  1371. * Array with pointer buttons status.
  1372. */
  1373. this.keys = new Array(5);
  1374. /**
  1375. * Pointer position inside of the window (coordinates in window space).
  1376. */
  1377. this.position = new Vector2(0, 0);
  1378. /**
  1379. * Pointer movement (coordinates in window space).
  1380. */
  1381. this.delta = new Vector2(0, 0);
  1382. /**
  1383. * Pointer scroll wheel movement.
  1384. */
  1385. this.wheel = 0;
  1386. /**
  1387. * Indicates a button of the pointer was double clicked.
  1388. */
  1389. this.doubleClicked = new Array(5);
  1390. /**
  1391. * DOM element where to attach the pointer events.
  1392. */
  1393. this.domElement = (domElement !== undefined) ? domElement : window;
  1394. /**
  1395. * Canvas attached to this pointer instance used to calculate position and delta in element space coordinates.
  1396. */
  1397. this.canvas = null;
  1398. if(canvas !== undefined)
  1399. {
  1400. this.setCanvas(canvas);
  1401. }
  1402. /**
  1403. * Event manager responsible for updating the raw data variables.
  1404. *
  1405. * Diferent events are used depending on the host platform.
  1406. *
  1407. * When the update method is called the raw data is reset.
  1408. */
  1409. this.events = new EventManager();
  1410. //Initialize key instances
  1411. for(var i = 0; i < 5; i++)
  1412. {
  1413. this._doubleClicked[i] = false;
  1414. this.doubleClicked[i] = false;
  1415. this._keys[i] = new Key();
  1416. this.keys[i] = new Key();
  1417. }
  1418. //Self pointer
  1419. var self = this;
  1420. //Scroll wheel
  1421. if(window.onmousewheel !== undefined)
  1422. {
  1423. //Chrome, edge
  1424. this.events.add(this.domElement, "mousewheel", function(event)
  1425. {
  1426. self._wheel = event.deltaY;
  1427. self._wheelUpdated = true;
  1428. });
  1429. }
  1430. else if(window.addEventListener !== undefined)
  1431. {
  1432. //Firefox
  1433. this.events.add(this.domElement, "DOMMouseScroll", function(event)
  1434. {
  1435. self._wheel = event.detail * 30;
  1436. self._wheelUpdated = true;
  1437. });
  1438. }
  1439. else
  1440. {
  1441. this.events.add(this.domElement, "wheel", function(event)
  1442. {
  1443. self._wheel = event.deltaY;
  1444. self._wheelUpdated = true;
  1445. });
  1446. }
  1447. //Touchscreen input events
  1448. if(window.ontouchstart !== undefined || navigator.msMaxTouchPoints > 0)
  1449. {
  1450. //Auxiliar variables to calculate touch delta
  1451. var lastTouch = new Vector2(0, 0);
  1452. //Touch start event
  1453. this.events.add(this.domElement, "touchstart", function(event)
  1454. {
  1455. var touch = event.touches[0];
  1456. self.updatePosition(touch.clientX, touch.clientY, 0, 0);
  1457. self.updateKey(Pointer.LEFT, Key.DOWN);
  1458. lastTouch.set(touch.clientX, touch.clientY);
  1459. });
  1460. //Touch end event
  1461. this.events.add(this.domElement, "touchend", function(event)
  1462. {
  1463. self.updateKey(Pointer.LEFT, Key.UP);
  1464. });
  1465. //Touch cancel event
  1466. this.events.add(this.domElement, "touchcancel", function(event)
  1467. {
  1468. self.updateKey(Pointer.LEFT, Key.UP);
  1469. });
  1470. //Touch move event
  1471. this.events.add(document.body, "touchmove", function(event)
  1472. {
  1473. var touch = event.touches[0];
  1474. self.updatePosition(touch.clientX, touch.clientY, touch.clientX - lastTouch.x, touch.clientY - lastTouch.y);
  1475. lastTouch.set(touch.clientX, touch.clientY);
  1476. });
  1477. }
  1478. //Move
  1479. this.events.add(this.domElement, "mousemove", function(event)
  1480. {
  1481. self.updatePosition(event.clientX, event.clientY, event.movementX, event.movementY);
  1482. });
  1483. //Button pressed
  1484. this.events.add(this.domElement, "mousedown", function(event)
  1485. {
  1486. self.updateKey(event.which - 1, Key.DOWN);
  1487. });
  1488. //Button released
  1489. this.events.add(this.domElement, "mouseup", function(event)
  1490. {
  1491. self.updateKey(event.which - 1, Key.UP);
  1492. });
  1493. //Drag start
  1494. this.events.add(this.domElement, "dragstart", function(event)
  1495. {
  1496. self.updateKey(event.which - 1, Key.UP);
  1497. });
  1498. //Pointer double click
  1499. this.events.add(this.domElement, "dblclick", function(event)
  1500. {
  1501. self._doubleClicked[event.which - 1] = true;
  1502. });
  1503. this.create();
  1504. }
  1505. Pointer.prototype = Pointer;
  1506. Pointer.prototype.constructor = Pointer;
  1507. /**
  1508. * Left pointer button.
  1509. */
  1510. Pointer.LEFT = 0;
  1511. /**
  1512. * Middle pointer button.
  1513. */
  1514. Pointer.MIDDLE = 1;
  1515. /**
  1516. * Right pointer button.
  1517. */
  1518. Pointer.RIGHT = 2;
  1519. /**
  1520. * Back pointer navigation button.
  1521. */
  1522. Pointer.BACK = 3;
  1523. /**
  1524. * Forward pointer navigation button.
  1525. */
  1526. Pointer.FORWARD = 4;
  1527. /**
  1528. * Element to be used for coordinates calculation relative to that canvas.
  1529. *
  1530. * @param {DOM} canvas Canvas to be attached to the Pointer instance
  1531. */
  1532. Pointer.setCanvas = function(element)
  1533. {
  1534. this.canvas = element;
  1535. element.pointerInside = false;
  1536. element.addEventListener("mouseenter", function()
  1537. {
  1538. this.pointerInside = true;
  1539. });
  1540. element.addEventListener("mouseleave", function()
  1541. {
  1542. this.pointerInside = false;
  1543. });
  1544. };
  1545. /**
  1546. * Check if pointer is inside attached canvas (updated async).
  1547. *
  1548. * @return {boolean} True if pointer is currently inside the canvas
  1549. */
  1550. Pointer.insideCanvas = function()
  1551. {
  1552. return this.canvas !== null && this.canvas.pointerInside;
  1553. };
  1554. /**
  1555. * Check if pointer button is currently pressed.
  1556. *
  1557. * @param {Number} button Button to check status of
  1558. * @return {boolean} True if button is currently pressed
  1559. */
  1560. Pointer.buttonPressed = function(button)
  1561. {
  1562. return this.keys[button].pressed;
  1563. };
  1564. /**
  1565. * Check if pointer button was double clicked.
  1566. *
  1567. * @param {Number} button Button to check status of
  1568. * @return {boolean} True if some pointer button was just double clicked
  1569. */
  1570. Pointer.buttonDoubleClicked = function(button)
  1571. {
  1572. return this.doubleClicked[button];
  1573. };
  1574. /**
  1575. * Check if a pointer button was just pressed.
  1576. *
  1577. * @param {Number} button Button to check status of
  1578. * @return {boolean} True if button was just pressed
  1579. */
  1580. Pointer.buttonJustPressed = function(button)
  1581. {
  1582. return this.keys[button].justPressed;
  1583. };
  1584. /**
  1585. * Check if a pointer button was just released.
  1586. *
  1587. * @param {Number} button Button to check status of
  1588. * @return {boolean} True if button was just released
  1589. */
  1590. Pointer.buttonJustReleased = function(button)
  1591. {
  1592. return this.keys[button].justReleased;
  1593. };
  1594. /**
  1595. * Update pointer position.
  1596. *
  1597. * Automatically called by the runtime.
  1598. *
  1599. * @param {Number} x
  1600. * @param {Number} y
  1601. * @param {Number} xDiff
  1602. * @param {Number} yDiff
  1603. */
  1604. Pointer.updatePosition = function(x, y, xDiff, yDiff)
  1605. {
  1606. if(this.canvas !== null)
  1607. {
  1608. var rect = this.canvas.getBoundingClientRect();
  1609. x -= rect.left;
  1610. y -= rect.top;
  1611. }
  1612. this._position.set(x, y);
  1613. this._delta.x += xDiff;
  1614. this._delta.y += yDiff;
  1615. this._positionUpdated = true;
  1616. };
  1617. /**
  1618. * Update a pointer button.
  1619. *
  1620. * Automatically called by the runtime.
  1621. *
  1622. * @param {Number} button
  1623. * @param {Number} action
  1624. */
  1625. Pointer.updateKey = function(button, action)
  1626. {
  1627. if(button > -1)
  1628. {
  1629. this._keys[button].update(action);
  1630. }
  1631. };
  1632. /**
  1633. * Update pointer buttons state, position, wheel and delta synchronously.
  1634. */
  1635. Pointer.update = function()
  1636. {
  1637. //Update pointer keys state
  1638. for(var i = 0; i < 5; i++)
  1639. {
  1640. if(this._keys[i].justPressed && this.keys[i].justPressed)
  1641. {
  1642. this._keys[i].justPressed = false;
  1643. }
  1644. if(this._keys[i].justReleased && this.keys[i].justReleased)
  1645. {
  1646. this._keys[i].justReleased = false;
  1647. }
  1648. this.keys[i].set(this._keys[i].justPressed, this._keys[i].pressed, this._keys[i].justReleased);
  1649. //Update pointer double click
  1650. if(this._doubleClicked[i] === true)
  1651. {
  1652. this.doubleClicked[i] = true;
  1653. this._doubleClicked[i] = false;
  1654. }
  1655. else
  1656. {
  1657. this.doubleClicked[i] = false;
  1658. }
  1659. }
  1660. //Update pointer wheel
  1661. if(this._wheelUpdated)
  1662. {
  1663. this.wheel = this._wheel;
  1664. this._wheelUpdated = false;
  1665. }
  1666. else
  1667. {
  1668. this.wheel = 0;
  1669. }
  1670. //Update pointer Position if needed
  1671. if(this._positionUpdated)
  1672. {
  1673. this.delta.copy(this._delta);
  1674. this.position.copy(this._position);
  1675. this._delta.set(0,0);
  1676. this._positionUpdated = false;
  1677. }
  1678. else
  1679. {
  1680. this.delta.x = 0;
  1681. this.delta.y = 0;
  1682. }
  1683. };
  1684. /**
  1685. * Create pointer events.
  1686. */
  1687. Pointer.create = function()
  1688. {
  1689. this.events.create();
  1690. };
  1691. /**
  1692. * Dispose pointer events.
  1693. */
  1694. Pointer.dispose = function()
  1695. {
  1696. this.events.destroy();
  1697. };
  1698. /**
  1699. * Viewport defines the user view into the content being rendered, similar to a camera it defines the size of the content, rotation and position of the content.
  1700. *
  1701. * The viewport can be moved, rotated and scaled to navigate the virtual canvas.
  1702. *
  1703. * @class
  1704. * @param {Element} canvas Canvas DOM element where the viewport is being rendered.
  1705. */
  1706. function Viewport(canvas)
  1707. {
  1708. /**
  1709. * UUID of the object.
  1710. */
  1711. this.uuid = UUID.generate();
  1712. /**
  1713. * Canvas DOM element where the viewport is being rendered.
  1714. */
  1715. this.canvas = canvas;
  1716. /**
  1717. * Position of the object.
  1718. */
  1719. this.position = new Vector2(0, 0);
  1720. /**
  1721. * Scale of the object.
  1722. */
  1723. this.scale = 1.0;
  1724. /**
  1725. * Rotation of the object relative to its center.
  1726. */
  1727. this.rotation = 0.0;
  1728. /**
  1729. * Local transformation matrix applied to the object.
  1730. */
  1731. this.matrix = new Matrix();
  1732. /**
  1733. * Inverse of the local transformation matrix.
  1734. */
  1735. this.inverseMatrix = new Matrix();
  1736. /**
  1737. * If true the matrix is updated before rendering the object.
  1738. */
  1739. this.matrixNeedsUpdate = true;
  1740. /**
  1741. * Flag to indicate if the viewport should move when scaling.
  1742. *
  1743. * For some application its easier to focus the target if the viewport moves to the pointer location while scaling.
  1744. */
  1745. this.moveOnScale = false;
  1746. /**
  1747. * Value of the initial point of rotation if the viewport is being rotated.
  1748. *
  1749. * Is set to null when the viewport is not being rotated.
  1750. */
  1751. this.rotationPoint = null;
  1752. }
  1753. /**
  1754. * Calculate and update the viewport transformation matrix.
  1755. *
  1756. * Also updates the inverse matrix of the viewport.
  1757. */
  1758. Viewport.prototype.updateMatrix = function()
  1759. {
  1760. if(this.matrixNeedsUpdate)
  1761. {
  1762. this.matrix.m = [1, 0, 0, 1, this.position.x, this.position.y];
  1763. if(this.rotation !== 0)
  1764. {
  1765. var c = Math.cos(this.rotation);
  1766. var s = Math.sin(this.rotation);
  1767. this.matrix.multiply(new Matrix([c, s, -s, c, 0, 0]));
  1768. }
  1769. if(this.scale !== 1)
  1770. {
  1771. this.matrix.scale(this.scale, this.scale);
  1772. }
  1773. this.inverseMatrix = this.matrix.getInverse();
  1774. this.matrixNeedsUpdate = false;
  1775. }
  1776. };
  1777. /**
  1778. * Center the viewport relative to a object.
  1779. *
  1780. * The position of the object is used a central point, this method does not consider "box" attributes or other strucures in the object.
  1781. *
  1782. * @param {Object2D} object Object to be centered on the viewport.
  1783. * @param {Element} canvas Canvas element where the image is drawn.
  1784. */
  1785. Viewport.prototype.centerObject = function(object, canvas)
  1786. {
  1787. var position = object.globalMatrix.transformPoint(new Vector2());
  1788. position.multiplyScalar(-this.scale);
  1789. position.x += canvas.width / 2;
  1790. position.y += canvas.height / 2;
  1791. this.position.copy(position);
  1792. this.matrixNeedsUpdate = true;
  1793. };
  1794. /**
  1795. * Viewport controls are used to allow the user to control the viewport.
  1796. *
  1797. * @class
  1798. * @param {Viewport} viewport
  1799. */
  1800. function ViewportControls(viewport)
  1801. {
  1802. /**
  1803. * Viewport being controlled by this object.
  1804. */
  1805. this.viewport = viewport;
  1806. /**
  1807. * Button used to drag and viewport around.
  1808. *
  1809. * On touch enabled devices the touch event is represented as a LEFT button.
  1810. */
  1811. this.dragButton = Pointer.RIGHT;
  1812. /**
  1813. * Is set to true allow the viewport to be scalled.
  1814. *
  1815. * Scaling is performed using the pointer scroll.
  1816. */
  1817. this.allowScale = true;
  1818. /**
  1819. * Flag to indicate if the viewport should move when scalling.
  1820. *
  1821. * For some application its easier to focus the target if the viewport moves to the pointer location while scalling.
  1822. */
  1823. this.moveOnScale = false;
  1824. /**
  1825. * If true allows the viewport to be rotated.
  1826. *
  1827. * Rotation is performed by holding the RIGHT and LEFT pointer buttons and rotating around the initial point.
  1828. */
  1829. this.allowRotation = true;
  1830. /**
  1831. * Value of the initial point of rotation if the viewport is being rotated.
  1832. *
  1833. * Is set to null when the viewport is not being rotated.
  1834. */
  1835. this.rotationPoint = null;
  1836. /**
  1837. * Initial rotation of the viewport.
  1838. */
  1839. this.rotationInitial = 0;
  1840. }
  1841. /**
  1842. * Update the viewport controls using the pointer object.
  1843. *
  1844. * Should be called every frame before rendering.
  1845. *
  1846. * @param {Pointer} pointer
  1847. */
  1848. ViewportControls.prototype.update = function(pointer)
  1849. {
  1850. // Scale
  1851. if(this.allowScale && pointer.wheel !== 0)
  1852. {
  1853. var scale = pointer.wheel * 1e-3 * this.viewport.scale;
  1854. this.viewport.scale -= scale;
  1855. this.viewport.matrixNeedsUpdate = true;
  1856. // Move on scale
  1857. if(this.moveOnScale && pointer.canvas !== null)
  1858. {
  1859. this.viewport.updateMatrix();
  1860. var pointerWorld = this.viewport.inverseMatrix.transformPoint(pointer.position);
  1861. var centerWorld = new Vector2(pointer.canvas.width / 2.0, pointer.canvas.height / 2.0);
  1862. centerWorld = this.viewport.inverseMatrix.transformPoint(centerWorld);
  1863. var delta = pointerWorld.clone();
  1864. delta.sub(centerWorld);
  1865. delta.multiplyScalar(0.1);
  1866. this.viewport.position.sub(delta);
  1867. this.viewport.matrixNeedsUpdate = true;
  1868. }
  1869. }
  1870. // Rotation
  1871. if(this.allowRotation && pointer.buttonPressed(Pointer.RIGHT) && pointer.buttonPressed(Pointer.LEFT))
  1872. {
  1873. // Rotation pivot
  1874. if(this.rotationPoint === null)
  1875. {
  1876. this.rotationPoint = pointer.position.clone();
  1877. this.rotationInitial = this.viewport.rotation;
  1878. }
  1879. else
  1880. {
  1881. var pointer = pointer.position.clone();
  1882. pointer.sub(this.rotationPoint);
  1883. this.viewport.rotation = this.rotationInitial + pointer.angle();
  1884. this.viewport.matrixNeedsUpdate = true;
  1885. }
  1886. }
  1887. // Drag
  1888. else
  1889. {
  1890. this.rotationPoint = null;
  1891. if(pointer.buttonPressed(this.dragButton))
  1892. {
  1893. this.viewport.position.x += pointer.delta.x;
  1894. this.viewport.position.y += pointer.delta.y;
  1895. this.viewport.matrixNeedsUpdate = true;
  1896. }
  1897. }
  1898. };
  1899. /**
  1900. * The renderer is responsible for drawing the objects structure into the canvas element and manage its rendering state.
  1901. *
  1902. * @class
  1903. * @param {Element} canvas Canvas to render the content.
  1904. * @param {Object} options Renderer canvas options.
  1905. */
  1906. function Renderer(canvas, options)
  1907. {
  1908. if(options === undefined)
  1909. {
  1910. options =
  1911. {
  1912. alpha: true
  1913. };
  1914. }
  1915. /**
  1916. * Canvas DOM element, has to be managed by the user.
  1917. */
  1918. this.canvas = canvas;
  1919. /**
  1920. * Canvas 2D rendering context used to draw content.
  1921. */
  1922. this.context = canvas.getContext("2d", {alpha: options.alpha});
  1923. this.context.imageSmoothingEnabled = true;
  1924. this.context.globalCompositeOperation = "source-over";
  1925. /**
  1926. * Pointer input handler object.
  1927. */
  1928. this.pointer = new Pointer(window, canvas);
  1929. /**
  1930. * Indicates if the canvas should be automatically cleared before new frame is drawn.
  1931. *
  1932. * If set to false the user should clear the frame before drawing.
  1933. */
  1934. this.autoClear = true;
  1935. }
  1936. /**
  1937. * Creates a infinite render loop to render the group into a viewport each frame.
  1938. *
  1939. * The render loop cannot be destroyed, and it automatically creates a viewport controls object.
  1940. *
  1941. * @param {Object2D} group Group to be rendered.
  1942. * @param {Viewport} viewport Viewport into the objects.
  1943. * @param {Function} onUpdate Function called before rendering the frame.
  1944. */
  1945. Renderer.prototype.createRenderLoop = function(group, viewport, onUpdate)
  1946. {
  1947. var self = this;
  1948. var controls = new ViewportControls(viewport);
  1949. function loop()
  1950. {
  1951. if(onUpdate !== undefined)
  1952. {
  1953. onUpdate();
  1954. }
  1955. controls.update(self.pointer);
  1956. self.update(group, viewport);
  1957. requestAnimationFrame(loop);
  1958. }
  1959. loop();
  1960. };
  1961. /**
  1962. * Update the renderer state, update the input handlers, calculate the object and viewport transformation matrices.
  1963. *
  1964. * Render the object using the viewport into a canvas element.
  1965. *
  1966. * The canvas state is saved and restored for each individual object, ensuring that the code of one object does not affect another one.
  1967. *
  1968. * Should be called at a fixed rate preferably using the requestAnimationFrame() method, its also possible to use the createRenderLoop() method, that automatically creates a infinite render loop.
  1969. *
  1970. * @param object {Object2D} Object to be updated and drawn into the canvas, the Object2D should be used as a group to store all the other objects to be updated and drawn.
  1971. * @param viewport {Viewport} Viewport to be updated (should be the one where the objects will be rendered after).
  1972. */
  1973. Renderer.prototype.update = function(object, viewport)
  1974. {
  1975. // Get objects to be rendered
  1976. var objects = [];
  1977. object.traverse(function(child)
  1978. {
  1979. if(child.visible)
  1980. {
  1981. objects.push(child);
  1982. }
  1983. });
  1984. // Sort objects by layer
  1985. objects.sort(function(a, b)
  1986. {
  1987. if(b.layer === a.layer)
  1988. {
  1989. return b.level - a.level;
  1990. }
  1991. return b.layer - a.layer;
  1992. });
  1993. // Pointer object update
  1994. var pointer = this.pointer;
  1995. pointer.update();
  1996. // Viewport transform matrix
  1997. viewport.updateMatrix();
  1998. // Project pointer coordinates
  1999. var point = pointer.position.clone();
  2000. var viewportPoint = viewport.inverseMatrix.transformPoint(point);
  2001. // Object pointer events
  2002. for(var i = 0; i < objects.length; i++)
  2003. {
  2004. var child = objects[i];
  2005. //Process the
  2006. if(child.pointerEvents)
  2007. {
  2008. var childPoint = child.inverseGlobalMatrix.transformPoint(child.ignoreViewport ? point : viewportPoint);
  2009. // Check if the pointer pointer is inside
  2010. if(child.isInside(childPoint))
  2011. {
  2012. // Pointer enter
  2013. if(!child.pointerInside && child.onPointerEnter !== null)
  2014. {
  2015. child.onPointerEnter(pointer, viewport);
  2016. }
  2017. // Pointer over
  2018. if(child.onPointerOver !== null)
  2019. {
  2020. child.onPointerOver(pointer, viewport);
  2021. }
  2022. // Double click
  2023. if(pointer.buttonDoubleClicked(Pointer.LEFT) && child.onDoubleClick !== null)
  2024. {
  2025. child.onDoubleClick(pointer, viewport);
  2026. }
  2027. // Pointer pressed
  2028. if(pointer.buttonPressed(Pointer.LEFT) && child.onButtonPressed !== null)
  2029. {
  2030. child.onButtonPressed(pointer, viewport);
  2031. }
  2032. // Just released
  2033. if(pointer.buttonJustReleased(Pointer.LEFT) && child.onButtonUp !== null)
  2034. {
  2035. child.onButtonUp(pointer, viewport);
  2036. }
  2037. // Pointer just pressed
  2038. if(pointer.buttonJustPressed(Pointer.LEFT))
  2039. {
  2040. if(child.onButtonDown !== null)
  2041. {
  2042. child.onButtonDown(pointer, viewport);
  2043. }
  2044. // Drag object and break to only start a drag operation on the top element.
  2045. if(child.draggable)
  2046. {
  2047. child.beingDragged = true;
  2048. break;
  2049. }
  2050. }
  2051. child.pointerInside = true;
  2052. }
  2053. else if(child.pointerInside)
  2054. {
  2055. // Pointer leave
  2056. if(child.onPointerLeave !== null)
  2057. {
  2058. child.onPointerLeave(pointer, viewport);
  2059. }
  2060. child.pointerInside = false;
  2061. }
  2062. // Stop object drag
  2063. if(pointer.buttonJustReleased(Pointer.LEFT))
  2064. {
  2065. if(child.draggable)
  2066. {
  2067. child.beingDragged = false;
  2068. }
  2069. }
  2070. }
  2071. }
  2072. // Object drag events and update logic
  2073. for(var i = 0; i < objects.length; i++)
  2074. {
  2075. var child = objects[i];
  2076. // Pointer drag event
  2077. if(child.beingDragged)
  2078. {
  2079. var lastPosition = pointer.position.clone();
  2080. lastPosition.sub(pointer.delta);
  2081. var positionWorld = viewport.inverseMatrix.transformPoint(pointer.position);
  2082. var lastWorld = viewport.inverseMatrix.transformPoint(lastPosition);
  2083. // Mouse delta in world coordinates
  2084. positionWorld.sub(lastWorld);
  2085. if(child.onPointerDrag !== null)
  2086. {
  2087. child.onPointerDrag(pointer, viewport, positionWorld);
  2088. }
  2089. }
  2090. // On update
  2091. if(child.onUpdate !== null)
  2092. {
  2093. child.onUpdate();
  2094. }
  2095. }
  2096. // Update transformation matrices
  2097. object.traverse(function(child)
  2098. {
  2099. child.updateMatrix();
  2100. });
  2101. this.context.setTransform(1, 0, 0, 1, 0, 0);
  2102. // Clear canvas content
  2103. if(this.autoClear)
  2104. {
  2105. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  2106. }
  2107. // Render into the canvas
  2108. for(var i = objects.length - 1; i >= 0; i--)
  2109. {
  2110. if(objects[i].isMask)
  2111. {
  2112. continue;
  2113. }
  2114. if(objects[i].saveContextState)
  2115. {
  2116. this.context.save();
  2117. }
  2118. // Apply all masks
  2119. var masks = objects[i].masks;
  2120. for(var j = 0; j < masks.length; j++)
  2121. {
  2122. if(!masks[j].ignoreViewport)
  2123. {
  2124. viewport.matrix.setContextTransform(this.context);
  2125. }
  2126. masks[j].transform(this.context, viewport, this.canvas);
  2127. masks[j].clip(this.context, viewport, this.canvas);
  2128. }
  2129. // Set the viewport transform
  2130. if(!objects[i].ignoreViewport)
  2131. {
  2132. viewport.matrix.setContextTransform(this.context);
  2133. }
  2134. else if(masks.length > 0)
  2135. {
  2136. this.context.setTransform(1, 0, 0, 1, 0, 0);
  2137. }
  2138. // Apply the object transform to the canvas context
  2139. objects[i].transform(this.context, viewport, this.canvas);
  2140. // Style the canvas context
  2141. if(objects[i].style !== null)
  2142. {
  2143. objects[i].style(this.context, viewport, this.canvas);
  2144. }
  2145. // Draw content into the canvas.
  2146. if(objects[i].draw !== null)
  2147. {
  2148. objects[i].draw(this.context, viewport, this.canvas);
  2149. }
  2150. if(objects[i].restoreContextState)
  2151. {
  2152. this.context.restore();
  2153. }
  2154. }
  2155. };
  2156. /**
  2157. * Box is described by a minimum and maximum points.
  2158. *
  2159. * Can be used for collision detection with points and other boxes.
  2160. *
  2161. * @class
  2162. * @param {Vector2} min
  2163. * @param {Vector2} max
  2164. */
  2165. function Box2(min, max)
  2166. {
  2167. this.min = (min !== undefined) ? min : new Vector2();
  2168. this.max = (max !== undefined) ? max : new Vector2();
  2169. }
  2170. /**
  2171. * Set the box values.
  2172. *
  2173. * @param {Vector2} min
  2174. * @param {Vector2} max
  2175. */
  2176. Box2.prototype.set = function(min, max)
  2177. {
  2178. this.min.copy(min);
  2179. this.max.copy(max);
  2180. return this;
  2181. };
  2182. /**
  2183. * Set the box from a list of Vector2 points.
  2184. *
  2185. * @param {Array} points
  2186. */
  2187. Box2.prototype.setFromPoints = function(points)
  2188. {
  2189. this.min = new Vector2(+Infinity, +Infinity);
  2190. this.max = new Vector2(-Infinity, -Infinity);
  2191. for(var i = 0, il = points.length; i < il; i++)
  2192. {
  2193. this.expandByPoint(points[i]);
  2194. }
  2195. return this;
  2196. };
  2197. /**
  2198. * Set the box minimum and maximum from center point and size.
  2199. *
  2200. * @param {Vector2} center
  2201. * @param {Vector2} size
  2202. */
  2203. Box2.prototype.setFromCenterAndSize = function(center, size)
  2204. {
  2205. var v1 = new Vector2();
  2206. var halfSize = v1.copy(size).multiplyScalar(0.5);
  2207. this.min.copy(center).sub(halfSize);
  2208. this.max.copy(center).add(halfSize);
  2209. return this;
  2210. };
  2211. /**
  2212. * Clone the box into a new object.
  2213. *
  2214. * Should be used when it it necessary to make operations to this box.
  2215. *
  2216. * @return {Box2} New box object with the copy of this object.
  2217. */
  2218. Box2.prototype.clone = function()
  2219. {
  2220. var box = new Box2();
  2221. box.copy(this);
  2222. return box;
  2223. };
  2224. /**
  2225. * Copy the box value from another box.
  2226. *
  2227. * @param {Box2} point
  2228. */
  2229. Box2.prototype.copy = function(box)
  2230. {
  2231. this.min.copy(box.min);
  2232. this.max.copy(box.max);
  2233. };
  2234. /**
  2235. * Check if the box is empty (size equals zero or is negative).
  2236. *
  2237. * The box size is condireded valid on two negative axis.
  2238. *
  2239. * @return {boolean} True if the box is empty.
  2240. */
  2241. Box2.prototype.isEmpty = function()
  2242. {
  2243. return (this.max.x < this.min.x) || (this.max.y < this.min.y);
  2244. };
  2245. /**
  2246. * Calculate the center point of the box.
  2247. *
  2248. * @param {Vector2} [target] Vector to store the result.
  2249. * @return {Vector2} Central point of the box.
  2250. */
  2251. Box2.prototype.getCenter = function(target)
  2252. {
  2253. if(target === undefined)
  2254. {
  2255. target = new Vector2();
  2256. }
  2257. this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2258. return target;
  2259. };
  2260. /**
  2261. * Get the size of the box from its min and max points.
  2262. *
  2263. * @param {Vector2} [target] Vector to store the result.
  2264. * @return {Vector2} Vector with the calculated size.
  2265. */
  2266. Box2.prototype.getSize = function(target)
  2267. {
  2268. if(target === undefined)
  2269. {
  2270. target = new Vector2();
  2271. }
  2272. this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  2273. return target;
  2274. };
  2275. /**
  2276. * Expand the box to contain a new point.
  2277. *
  2278. * @param {Vector2} point
  2279. */
  2280. Box2.prototype.expandByPoint = function(point)
  2281. {
  2282. this.min.min(point);
  2283. this.max.max(point);
  2284. return this;
  2285. };
  2286. /**
  2287. * Expand the box by adding a border with the vector size.
  2288. *
  2289. * Vector is subtracted from min and added to the max points.
  2290. *
  2291. * @param {Vector2} vector
  2292. */
  2293. Box2.prototype.expandByVector = function(vector)
  2294. {
  2295. this.min.sub(vector);
  2296. this.max.add(vector);
  2297. };
  2298. /**
  2299. * Expand the box by adding a border with the scalar value.
  2300. *
  2301. * @param {number} scalar
  2302. */
  2303. Box2.prototype.expandByScalar = function(scalar)
  2304. {
  2305. this.min.addScalar(-scalar);
  2306. this.max.addScalar(scalar);
  2307. };
  2308. /**
  2309. * Check if the box contains a point inside.
  2310. *
  2311. * @param {Vector2} point
  2312. * @return {boolean} True if the box contains point.
  2313. */
  2314. Box2.prototype.containsPoint = function(point)
  2315. {
  2316. return !(point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y);
  2317. };
  2318. /**
  2319. * Check if the box fully contains another box inside (different from intersects box).
  2320. *
  2321. * Only returns true if the box is fully contained.
  2322. *
  2323. * @param {Box2} box
  2324. * @return {boolean} True if the box contains box.
  2325. */
  2326. Box2.prototype.containsBox = function(box)
  2327. {
  2328. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  2329. };
  2330. /**
  2331. * Check if two boxes intersect each other, using 4 splitting planes to rule out intersections.
  2332. *
  2333. * @param {Box2} box
  2334. * @return {boolean} True if the boxes intersect each other.
  2335. */
  2336. Box2.prototype.intersectsBox = function(box)
  2337. {
  2338. return !(box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y);
  2339. };
  2340. /**
  2341. * Calculate the distance to a point.
  2342. *
  2343. * @param {Vector2} point
  2344. * @return {number} Distance to point calculated.
  2345. */
  2346. Box2.prototype.distanceToPoint = function(point)
  2347. {
  2348. var v = new Vector2();
  2349. var clampedPoint = v.copy(point).clamp(this.min, this.max);
  2350. return clampedPoint.sub(point).length();
  2351. };
  2352. /**
  2353. * Make a intersection between this box and another box.
  2354. *
  2355. * Store the result in this object.
  2356. *
  2357. * @param {Box2} box
  2358. */
  2359. Box2.prototype.intersect = function(box)
  2360. {
  2361. this.min.max(box.min);
  2362. this.max.min(box.max);
  2363. };
  2364. /**
  2365. * Make a union between this box and another box.
  2366. *
  2367. * Store the result in this object.
  2368. *
  2369. * @param {Box2} box
  2370. */
  2371. Box2.prototype.union = function(box)
  2372. {
  2373. this.min.min(box.min);
  2374. this.max.max(box.max);
  2375. };
  2376. /**
  2377. * Translate the box by a offset value, adds the offset to booth min and max.
  2378. *
  2379. * @param {Vector2} offset
  2380. */
  2381. Box2.prototype.translate = function(offset)
  2382. {
  2383. this.min.add(offset);
  2384. this.max.add(offset);
  2385. };
  2386. /**
  2387. * Checks if two boxes are equal.
  2388. *
  2389. * @param {Box2} box
  2390. * @return {boolean} True if the two boxes are equal.
  2391. */
  2392. Box2.prototype.equals = function(box)
  2393. {
  2394. return box.min.equals(this.min) && box.max.equals(this.max);
  2395. };
  2396. /**
  2397. * A mask can be used to set the drawing region.
  2398. *
  2399. * Masks are treated as objects their shape is used to filter other objects shape.
  2400. *
  2401. * Multiple mask objects can be active simultaneously, they have to be attached to the object mask list to filter the render region.
  2402. *
  2403. * A mask objects is draw using the context.clip() method.
  2404. *
  2405. * @class
  2406. * @extends {Object2D}
  2407. */
  2408. function Mask()
  2409. {
  2410. Object2D.call(this);
  2411. }
  2412. Mask.prototype = Object.create(Object2D.prototype);
  2413. Mask.prototype.isMask = true;
  2414. /**
  2415. * Clip the canvas context, to ensure that next objects being drawn are cliped to the path stored here.
  2416. *
  2417. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  2418. * @param {Viewport} viewport Viewport applied to the canvas.
  2419. * @param {DOM} canvas DOM canvas element where the content is being drawn.
  2420. */
  2421. Mask.prototype.clip = function(context, viewport, canvas){};
  2422. /**
  2423. * Box mask can be used to clear a box mask region.
  2424. *
  2425. * It will limit the drawing region to this box.
  2426. *
  2427. * @class
  2428. * @extends {Mask}
  2429. */
  2430. function BoxMask()
  2431. {
  2432. Mask.call(this);
  2433. /**
  2434. * Box object containing the size of the object.
  2435. */
  2436. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  2437. /**
  2438. * If inverted the mask considers the outside of the box instead of the inside.
  2439. */
  2440. this.invert = false;
  2441. }
  2442. BoxMask.prototype = Object.create(Mask.prototype);
  2443. BoxMask.prototype.isInside = function(point)
  2444. {
  2445. return this.box.containsPoint(point);
  2446. };
  2447. BoxMask.prototype.clip = function(context, viewport, canvas)
  2448. {
  2449. context.beginPath();
  2450. var width = this.box.max.x - this.box.min.x;
  2451. if(this.invert)
  2452. {
  2453. context.rect(this.box.min.x - 1e4, -5e3, 1e4, 1e4);
  2454. context.rect(this.box.max.x, -5e3, 1e4, 1e4);
  2455. context.rect(this.box.min.x, this.box.min.y - 1e4, width, 1e4);
  2456. context.rect(this.box.min.x, this.box.max.y, width, 1e4);
  2457. }
  2458. else
  2459. {
  2460. var height = this.box.max.y - this.box.min.y;
  2461. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  2462. }
  2463. context.clip();
  2464. };
  2465. /**
  2466. * Box object draw a rectangular object.
  2467. *
  2468. * Can be used as a base to implement other box objects, already implements collision for pointer events.
  2469. *
  2470. * @class
  2471. * @extends {Object2D}
  2472. */
  2473. function Box()
  2474. {
  2475. Object2D.call(this);
  2476. /**
  2477. * Box object containing the size of the object.
  2478. */
  2479. this.box = new Box2(new Vector2(-50, -50), new Vector2(50, 50));
  2480. /**
  2481. * Style of the object border line.
  2482. *
  2483. * If set null it is ignored.
  2484. */
  2485. this.strokeStyle = "#000000";
  2486. /**
  2487. * Line width, only used if a valid strokeStyle is defined.
  2488. */
  2489. this.lineWidth = 1;
  2490. /**
  2491. * Background color of the box.
  2492. *
  2493. * If set null it is ignored.
  2494. */
  2495. this.fillStyle = "#FFFFFF";
  2496. }
  2497. Box.prototype = Object.create(Object2D.prototype);
  2498. Box.prototype.onPointerEnter = function(pointer, viewport)
  2499. {
  2500. this.fillStyle = "#CCCCCC";
  2501. };
  2502. Box.prototype.onPointerLeave = function(pointer, viewport)
  2503. {
  2504. this.fillStyle = "#FFFFFF";
  2505. };
  2506. Box.prototype.isInside = function(point)
  2507. {
  2508. return this.box.containsPoint(point);
  2509. };
  2510. Box.prototype.draw = function(context, viewport, canvas)
  2511. {
  2512. var width = this.box.max.x - this.box.min.x;
  2513. var height = this.box.max.y - this.box.min.y;
  2514. if(this.fillStyle !== null)
  2515. {
  2516. context.fillStyle = this.fillStyle;
  2517. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  2518. }
  2519. if(this.strokeStyle !== null)
  2520. {
  2521. context.lineWidth = this.lineWidth;
  2522. context.strokeStyle = this.strokeStyle;
  2523. context.strokeRect(this.box.min.x, this.box.min.y, width, height);
  2524. }
  2525. };
  2526. /**
  2527. * Circle object draw a circular object, into the canvas.
  2528. *
  2529. * Can be used as a base to implement other circular objects, already implements the circle collision for pointer events.
  2530. *
  2531. * @class
  2532. * @extends {Object2D}
  2533. */
  2534. function Circle()
  2535. {
  2536. Object2D.call(this);
  2537. /**
  2538. * Radius of the circle.
  2539. */
  2540. this.radius = 10.0;
  2541. /**
  2542. * Style of the object border line.
  2543. *
  2544. * If set null it is ignored.
  2545. */
  2546. this.strokeStyle = "#000000";
  2547. /**
  2548. * Line width, only used if a valid strokeStyle is defined.
  2549. */
  2550. this.lineWidth = 1;
  2551. /**
  2552. * Background color of the circle.
  2553. *
  2554. * If set null it is ignored.
  2555. */
  2556. this.fillStyle = "#FFFFFF";
  2557. }
  2558. Circle.prototype = Object.create(Object2D.prototype);
  2559. Circle.prototype.isInside = function(point)
  2560. {
  2561. return point.length() <= this.radius;
  2562. };
  2563. Circle.prototype.onPointerEnter = function(pointer, viewport)
  2564. {
  2565. this.fillStyle = "#CCCCCC";
  2566. };
  2567. Circle.prototype.onPointerLeave = function(pointer, viewport)
  2568. {
  2569. this.fillStyle = "#FFFFFF";
  2570. };
  2571. Circle.prototype.draw = function(context, viewport, canvas)
  2572. {
  2573. context.beginPath();
  2574. context.arc(0, 0, this.radius, 0, 2 * Math.PI);
  2575. if(this.fillStyle !== null)
  2576. {
  2577. context.fillStyle = this.fillStyle;
  2578. context.fill();
  2579. }
  2580. if(this.strokeStyle !== null)
  2581. {
  2582. context.lineWidth = this.lineWidth;
  2583. context.strokeStyle = this.strokeStyle;
  2584. context.stroke();
  2585. }
  2586. };
  2587. /**
  2588. * Line object draw a line from one point to another without any kind of interpolation.
  2589. *
  2590. * For drawing lines with interpolation check {BezierCurve}
  2591. *
  2592. * @class
  2593. * @extends {Object2D}
  2594. */
  2595. function Line()
  2596. {
  2597. Object2D.call(this);
  2598. /**
  2599. * Initial point of the line.
  2600. *
  2601. * Can be equal to the position object of another object. Making it automatically follow that object.
  2602. */
  2603. this.from = new Vector2();
  2604. /**
  2605. * Final point of the line.
  2606. *
  2607. * Can be equal to the position object of another object. Making it automatically follow that object.
  2608. */
  2609. this.to = new Vector2();
  2610. /**
  2611. * Dash line pattern to be used, if empty draws a solid line.
  2612. *
  2613. * Dash pattern is defined as the size of dashes as pairs of space with no line and with line.
  2614. *
  2615. * E.g if the dash pattern is [1, 2] we get 1 point with line, 2 without line repeat infinitelly.
  2616. */
  2617. this.dashPattern = [5, 5];
  2618. /**
  2619. * Style of the object line.
  2620. */
  2621. this.strokeStyle = "#000000";
  2622. /**
  2623. * Line width of the line.
  2624. */
  2625. this.lineWidth = 1;
  2626. }
  2627. Line.prototype = Object.create(Object2D.prototype);
  2628. Line.prototype.style = function(context, viewport, canvas)
  2629. {
  2630. context.lineWidth = this.lineWidth;
  2631. context.strokeStyle = this.strokeStyle;
  2632. context.setLineDash(this.dashPattern);
  2633. };
  2634. Line.prototype.draw = function(context, viewport, canvas)
  2635. {
  2636. context.beginPath();
  2637. context.moveTo(this.from.x, this.from.y);
  2638. context.lineTo(this.to.x, this.to.y);
  2639. context.stroke();
  2640. };
  2641. /**
  2642. * Image object is used to draw an image from URL.
  2643. *
  2644. * @class
  2645. * @param {string} src Source URL of the image.
  2646. * @extends {Object2D}
  2647. */
  2648. function Image(src)
  2649. {
  2650. Object2D.call(this);
  2651. /**
  2652. * Box object containing the size of the object.
  2653. */
  2654. this.box = new Box2();
  2655. /**
  2656. * Image source DOM element.
  2657. */
  2658. this.image = document.createElement("img");
  2659. if(src !== undefined)
  2660. {
  2661. this.setImage(src);
  2662. }
  2663. }
  2664. Image.prototype = Object.create(Object2D.prototype);
  2665. /**
  2666. * Set the image of the object.
  2667. *
  2668. * Automatically sets the box size to match the image.
  2669. *
  2670. * @param {string} src Source URL of the image.
  2671. */
  2672. Image.prototype.setImage = function(src)
  2673. {
  2674. var self = this;
  2675. this.image.onload = function()
  2676. {
  2677. self.box.min.set(0, 0);
  2678. self.box.max.set(this.naturalWidth, this.naturalHeight);
  2679. };
  2680. this.image.src = src;
  2681. };
  2682. Image.prototype.isInside = function(point)
  2683. {
  2684. return this.box.containsPoint(point);
  2685. };
  2686. Image.prototype.draw = function(context, viewport, canvas)
  2687. {
  2688. if(this.image.src.length > 0)
  2689. {
  2690. context.drawImage(this.image, 0, 0, this.image.naturalWidth, this.image.naturalHeight, this.box.min.x, this.box.min.y, this.box.max.x - this.box.min.x, this.box.max.y - this.box.min.y);
  2691. }
  2692. };
  2693. /**
  2694. * A DOM object transformed using CSS3D to ver included in the graph.
  2695. *
  2696. * DOM objects always stay on top of everything else, mouse events are not supported for these objects.
  2697. *
  2698. * Use the DOM events for interaction with these types of objects.
  2699. *
  2700. * @class
  2701. * @param {Element} parentDOM Parent DOM element that contains the drawing canvas.
  2702. * @param {string} type Type of the DOM element (e.g. "div", "p", ...)
  2703. * @extends {Object2D}
  2704. */
  2705. function DOM(parentDOM, type)
  2706. {
  2707. Object2D.call(this);
  2708. /**
  2709. * Parent element that contains this DOM div.
  2710. */
  2711. this.parentDOM = parentDOM;
  2712. /**
  2713. * DOM element contained by this object.
  2714. *
  2715. * Bye default it has the pointerEvents style set to none.
  2716. */
  2717. this.element = document.createElement("div");
  2718. this.element.style.transformStyle = "preserve-3d";
  2719. this.element.style.position = "absolute";
  2720. this.element.style.top = "0px";
  2721. this.element.style.bottom = "0px";
  2722. this.element.style.transformOrigin = "0px 0px";
  2723. this.element.style.overflow = "auto";
  2724. this.element.style.pointerEvents = "none";
  2725. /**
  2726. * Size of the DOM element (in world coordinates).
  2727. */
  2728. this.size = new Vector2(100, 100);
  2729. }
  2730. DOM.prototype = Object.create(Object2D.prototype);
  2731. DOM.prototype.onAdd = function()
  2732. {
  2733. this.parentDOM.appendChild(this.element);
  2734. };
  2735. DOM.prototype.onRemove = function()
  2736. {
  2737. this.parentDOM.removeChild(this.element);
  2738. };
  2739. DOM.prototype.transform = function(context, viewport, canvas)
  2740. {
  2741. // CSS transformation matrix
  2742. if(this.ignoreViewport)
  2743. {
  2744. this.element.style.transform = this.globalMatrix.cssTransform();
  2745. }
  2746. else
  2747. {
  2748. var projection = viewport.matrix.clone();
  2749. projection.multiply(this.globalMatrix);
  2750. this.element.style.transform = projection.cssTransform();
  2751. }
  2752. // Size of the element
  2753. this.element.style.width = this.size.x + "px";
  2754. this.element.style.height = this.size.y + "px";
  2755. // Visibility
  2756. this.element.style.display = this.visible ? "block" : "none";
  2757. };
  2758. /**
  2759. * Pattern object draw a image repeated as a pattern.
  2760. *
  2761. * Its similar to the Image class but the image can be repeat infinitely.
  2762. *
  2763. * @class
  2764. * @extends {Object2D}
  2765. * @param {string} src Source image URL.
  2766. */
  2767. function Pattern(src)
  2768. {
  2769. Object2D.call(this);
  2770. /**
  2771. * Box object containing the size of the object.
  2772. */
  2773. this.box = new Box2();
  2774. /**
  2775. * Image source DOM element.
  2776. */
  2777. this.image = document.createElement("img");
  2778. /**
  2779. * A DOMString indicating how to repeat the pattern image.
  2780. */
  2781. this.repetition = "repeat";
  2782. if(src !== undefined)
  2783. {
  2784. this.setImage(src);
  2785. }
  2786. }
  2787. Pattern.prototype = Object.create(Object2D.prototype);
  2788. /**
  2789. * Set the image of the object.
  2790. *
  2791. * Automatically sets the box size to match the image.
  2792. */
  2793. Pattern.prototype.setImage = function(src)
  2794. {
  2795. var self = this;
  2796. this.image.onload = function()
  2797. {
  2798. self.box.min.set(0, 0);
  2799. self.box.max.set(this.naturalWidth, this.naturalHeight);
  2800. };
  2801. this.image.src = src;
  2802. };
  2803. Pattern.prototype.isInside = function(point)
  2804. {
  2805. return this.box.containsPoint(point);
  2806. };
  2807. Pattern.prototype.draw = function(context, viewport, canvas)
  2808. {
  2809. var width = this.box.max.x - this.box.min.x;
  2810. var height = this.box.max.y - this.box.min.y;
  2811. if(this.image.src.length > 0)
  2812. {
  2813. var pattern = context.createPattern(this.image, this.repetition);
  2814. context.fillStyle = pattern;
  2815. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  2816. }
  2817. };
  2818. /**
  2819. * Graph object is used to draw simple graph data into the canvas.
  2820. *
  2821. * Graph data is composed of X, Y values.
  2822. *
  2823. * @class
  2824. * @extends {Object2D}
  2825. */
  2826. function Graph()
  2827. {
  2828. Object2D.call(this);
  2829. /**
  2830. * Graph object containing the size of the object.
  2831. */
  2832. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  2833. /**
  2834. * Color of the box border line.
  2835. */
  2836. this.strokeStyle = "rgb(0, 153, 255)";
  2837. /**
  2838. * Line width.
  2839. */
  2840. this.lineWidth = 1;
  2841. /**
  2842. * Background color of the box.
  2843. */
  2844. this.fillStyle = "rgba(0, 153, 255, 0.3)";
  2845. /**
  2846. * Minimum value of the graph.
  2847. */
  2848. this.min = 0;
  2849. /**
  2850. * Maximum value of the graph.
  2851. */
  2852. this.max = 10;
  2853. /**
  2854. * Data to be presented in the graph.
  2855. *
  2856. * The array should store numeric values.
  2857. */
  2858. this.data = [];
  2859. }
  2860. Graph.prototype = Object.create(Object2D.prototype);
  2861. Graph.prototype.isInside = function(point)
  2862. {
  2863. return this.box.containsPoint(point);
  2864. };
  2865. Graph.prototype.draw = function(context, viewport, canvas)
  2866. {
  2867. if(this.data.length === 0)
  2868. {
  2869. return;
  2870. }
  2871. var width = this.box.max.x - this.box.min.x;
  2872. var height = this.box.max.y - this.box.min.y;
  2873. context.lineWidth = this.lineWidth;
  2874. context.strokeStyle = this.strokeStyle;
  2875. context.beginPath();
  2876. var step = width / (this.data.length - 1);
  2877. var gamma = this.max - this.min;
  2878. context.moveTo(this.box.min.x, this.box.max.y - ((this.data[0] - this.min) / gamma) * height);
  2879. for(var i = 1, s = step; i < this.data.length; s += step, i++)
  2880. {
  2881. context.lineTo(this.box.min.x + s, this.box.max.y - ((this.data[i] - this.min) / gamma) * height);
  2882. }
  2883. context.stroke();
  2884. if(this.fillStyle !== null)
  2885. {
  2886. context.fillStyle = this.fillStyle;
  2887. context.lineTo(this.box.max.x, this.box.max.y);
  2888. context.lineTo(this.box.min.x, this.box.max.y);
  2889. context.fill();
  2890. }
  2891. };
  2892. /**
  2893. * Bezier curve object draw as bezier curve between two points.
  2894. *
  2895. * @class
  2896. * @extends {Line}
  2897. */
  2898. function BezierCurve()
  2899. {
  2900. Line.call(this);
  2901. /**
  2902. * Intial position control point, indicates the tangent of the bezier curve on the first point.
  2903. */
  2904. this.fromCp = new Vector2();
  2905. /**
  2906. * Final position control point, indicates the tangent of the bezier curve on the last point.
  2907. */
  2908. this.toCp = new Vector2();
  2909. }
  2910. BezierCurve.prototype = Object.create(Line.prototype);
  2911. /**
  2912. * Create a bezier curve helper, to edit the bezier curve anchor points.
  2913. *
  2914. * Helper objects are added to the parent of the curve object.
  2915. *
  2916. * @static
  2917. * @param {BezierCurve} object Object to create the helper for.
  2918. */
  2919. BezierCurve.curveHelper = function(object)
  2920. {
  2921. var fromCp = new Circle();
  2922. fromCp.radius = 3;
  2923. fromCp.layer = object.layer + 1;
  2924. fromCp.draggable = true;
  2925. fromCp.onPointerDrag = function(pointer, viewport, delta)
  2926. {
  2927. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  2928. object.fromCp.copy(fromCp.position);
  2929. };
  2930. object.parent.add(fromCp);
  2931. var fromLine = new Line();
  2932. fromLine.from = object.from;
  2933. fromLine.to = object.fromCp;
  2934. object.parent.add(fromLine);
  2935. var toCp = new Circle();
  2936. toCp.radius = 3;
  2937. toCp.layer = object.layer + 1;
  2938. toCp.draggable = true;
  2939. toCp.onPointerDrag = function(pointer, viewport, delta)
  2940. {
  2941. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  2942. object.toCp.copy(toCp.position);
  2943. };
  2944. object.parent.add(toCp);
  2945. var toLine = new Line();
  2946. toLine.from = object.to;
  2947. toLine.to = object.toCp;
  2948. object.parent.add(toLine);
  2949. };
  2950. BezierCurve.prototype.draw = function(context, viewport, canvas)
  2951. {
  2952. context.beginPath();
  2953. context.moveTo(this.from.x, this.from.y);
  2954. context.bezierCurveTo(this.fromCp.x, this.fromCp.y, this.toCp.x, this.toCp.y, this.to.x, this.to.y);
  2955. context.stroke();
  2956. };
  2957. /**
  2958. * Bezier curve object draw as bezier curve between two points.
  2959. *
  2960. * @class
  2961. * @extends {Object2D}
  2962. */
  2963. function QuadraticCurve()
  2964. {
  2965. Line.call(this);
  2966. /**
  2967. * Control point of the quadratic curve used to control the curvature of the line between the from and to point.
  2968. *
  2969. * The curve is interpolated in the direction of the control point it defined the path of the curve.
  2970. */
  2971. this.controlPoint = new Vector2();
  2972. }
  2973. QuadraticCurve.prototype = Object.create(Line.prototype);
  2974. /**
  2975. * Create a quadratic curve helper, to edit the curve control point.
  2976. *
  2977. * Helper objects are added to the parent of the curve object.
  2978. *
  2979. * @static
  2980. * @param {QuadraticCurve} object Object to create the helper for.
  2981. */
  2982. QuadraticCurve.curveHelper = function(object)
  2983. {
  2984. var fromLine = new Line();
  2985. fromLine.from = object.from;
  2986. fromLine.to = object.controlPoint;
  2987. object.parent.add(fromLine);
  2988. var controlPoint = new Circle();
  2989. controlPoint.radius = 3;
  2990. controlPoint.layer = object.layer + 1;
  2991. controlPoint.draggable = true;
  2992. controlPoint.position = object.controlPoint;
  2993. controlPoint.onPointerDrag = function(pointer, viewport, delta)
  2994. {
  2995. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  2996. object.controlPoint.copy(controlPoint.position);
  2997. };
  2998. object.parent.add(controlPoint);
  2999. var toLine = new Line();
  3000. toLine.from = object.to;
  3001. toLine.to = object.controlPoint;
  3002. object.parent.add(toLine);
  3003. };
  3004. QuadraticCurve.prototype.draw = function(context, viewport, canvas)
  3005. {
  3006. context.beginPath();
  3007. context.moveTo(this.from.x, this.from.y);
  3008. context.quadraticCurveTo(this.controlPoint.x, this.controlPoint.y, this.to.x, this.to.y);
  3009. context.stroke();
  3010. };
  3011. /**
  3012. * Node connector is used to connect a output of a node to a input of another node.
  3013. *
  3014. * Some nodes inputs/outputs might support just one or multiple connections.
  3015. *
  3016. * @class NodeConnector
  3017. */
  3018. function NodeConnector()
  3019. {
  3020. BezierCurve.call(this);
  3021. /**
  3022. * Origin hook that is attached to a node.
  3023. *
  3024. * @type {NodeHook}
  3025. */
  3026. this.outputHook = null;
  3027. /**
  3028. * Destination hook that is attached to a node.
  3029. *
  3030. * @type {NodeHook}
  3031. */
  3032. this.inputHook = null;
  3033. }
  3034. NodeConnector.prototype = Object.create(BezierCurve.prototype);
  3035. /**
  3036. * Represents a node hook point. Is attached to the node element and represented visually.
  3037. *
  3038. * Can be used as a node input, output or as a bidirectional connection.
  3039. *
  3040. * @class NodeHook
  3041. * @param {Node} node Node of this hook.
  3042. * @param {number} direction Direction of the hook.
  3043. */
  3044. function NodeHook(node, direction)
  3045. {
  3046. Circle.call(this);
  3047. this.radius = 6;
  3048. this.layer = 1;
  3049. /**
  3050. * Name of the hook presented to the user.
  3051. */
  3052. this.name = "";
  3053. /**
  3054. * Type of hook. Hooks of the same type can be connected.
  3055. *
  3056. * @type {string}
  3057. */
  3058. this.type = "";
  3059. /**
  3060. * If set true the hook can be connected to multiple hooks.
  3061. *
  3062. * @type {boolean}
  3063. */
  3064. this.multiple = false;
  3065. /**
  3066. * Direction of the node hook.
  3067. *
  3068. * @type {number}
  3069. */
  3070. this.direction = direction;
  3071. /**
  3072. * Node where this input element in attached.
  3073. *
  3074. * @type {Node}
  3075. */
  3076. this.node = node;
  3077. /**
  3078. * Node connector used to connect this hook to another node hook.
  3079. *
  3080. * @type {NodeConnector}
  3081. */
  3082. this.connector = null;
  3083. }
  3084. /**
  3085. * Input hook can only be connected to an output.
  3086. *
  3087. * Is used to read data from the output.
  3088. *
  3089. * @type {number}
  3090. */
  3091. NodeHook.INPUT = 1;
  3092. /**
  3093. * Output hook can only be connected to an input.
  3094. *
  3095. * Writes data to the output.
  3096. *
  3097. * @type {number}
  3098. */
  3099. NodeHook.OUTPUT = 2;
  3100. /**
  3101. * Bidirectional hook can be connected to any type of hook.
  3102. *
  3103. * Can be used to write and read from inputs and/or outputs.
  3104. *
  3105. * @type {number}
  3106. */
  3107. NodeHook.BIDIRECTIONAL = 3;
  3108. NodeHook.prototype = Object.create(Circle.prototype);
  3109. NodeHook.prototype.onButtonPressed = function()
  3110. {
  3111. // Create new connector
  3112. if(this.connector === null)
  3113. {
  3114. var connector = new NodeConnector();
  3115. if(this.direction === NodeHook.INPUT)
  3116. {
  3117. connector.inputHook = this;
  3118. }
  3119. else if(this.direction === NodeHook.OUTPUT)
  3120. {
  3121. connector.outputHook = this;
  3122. }
  3123. this.node.parent.add(connector);
  3124. }
  3125. };
  3126. /**
  3127. * Node objects can be connected between them to create graphs.
  3128. *
  3129. * Each node contains inputs, outputs and a set of attributes containing their state. Inputs can be connected to outputs of other nodes, and vice-versa.
  3130. *
  3131. * This class implements node basic functionality, the logic to connected node and define inputs/outputs of the nodes.
  3132. *
  3133. * @class Node
  3134. */
  3135. function Node()
  3136. {
  3137. Box.call(this);
  3138. this.draggable = true;
  3139. /**
  3140. * List of inputs of the node.
  3141. *
  3142. * @type {NodeHook[]}
  3143. */
  3144. this.inputs = [];
  3145. /**
  3146. * List of outputs of the node.
  3147. *
  3148. * @type {NodeHook[]}
  3149. */
  3150. this.outputs = [];
  3151. }
  3152. Node.prototype = Object.create(Box.prototype);
  3153. /**
  3154. * Add input to this node.
  3155. *
  3156. * @param type
  3157. */
  3158. Node.prototype.addInput = function(type)
  3159. {
  3160. var hook = new NodeHook(this, NodeHook.INPUT);
  3161. hook.type = type;
  3162. this.inputs.push(hook);
  3163. this.add(hook);
  3164. };
  3165. /**
  3166. * Add output hook to this node.
  3167. *
  3168. * @param type
  3169. */
  3170. Node.prototype.addOutput = function(type)
  3171. {
  3172. var hook = new NodeHook(this, NodeHook.OUTPUT);
  3173. hook.type = type;
  3174. this.outputs.push(hook);
  3175. this.add(hook);
  3176. };
  3177. Node.prototype.draw = function(context, viewport, canvas)
  3178. {
  3179. var height = this.box.max.y - this.box.min.y;
  3180. // Input hooks position
  3181. var step = height / (this.inputs.length + 1);
  3182. var start = this.box.min.y + step;
  3183. for(var i = 0; i < this.inputs.length; i++)
  3184. {
  3185. this.inputs[i].position.set(this.box.min.x, start + step * i);
  3186. }
  3187. // Output hooks position
  3188. var step = height / (this.outputs.length + 1);
  3189. var start = this.box.min.y + step;
  3190. for(var i = 0; i < this.outputs.length; i++)
  3191. {
  3192. this.outputs[i].position.set(this.box.max.x, start + step * i);
  3193. }
  3194. Box.prototype.draw.call(this, context, viewport, canvas);
  3195. };
  3196. /**
  3197. * Class contains helper functions to create editing object tools.
  3198. *
  3199. * @class
  3200. */
  3201. function Helpers(){}
  3202. /**
  3203. * Create a rotation tool helper.
  3204. *
  3205. * When the object is dragged is changes the parent object rotation.
  3206. *
  3207. * @static
  3208. */
  3209. Helpers.rotateTool = function(object)
  3210. {
  3211. var tool = new Circle();
  3212. tool.radius = 4;
  3213. tool.layer = object.layer + 1;
  3214. tool.onPointerDrag = function(pointer, viewport, delta)
  3215. {
  3216. object.rotation += delta.x * 1e-3;
  3217. };
  3218. object.add(tool);
  3219. };
  3220. /**
  3221. * Create a box resize helper and attach it to an object to change the size of the object box.
  3222. *
  3223. * Each helper is positioned on one corner of the box, and the value of the corner is copied to the boxes as they are dragged.
  3224. *
  3225. * This method required to object to have a box property.
  3226. *
  3227. * @static
  3228. */
  3229. Helpers.boxResizeTool = function(object)
  3230. {
  3231. if(object.box === undefined)
  3232. {
  3233. console.warn("escher.js: Helpers.boxResizeTool(), object box property missing.");
  3234. return;
  3235. }
  3236. function updateHelpers()
  3237. {
  3238. topRight.position.copy(object.box.min);
  3239. bottomLeft.position.copy(object.box.max);
  3240. topLeft.position.set(object.box.max.x, object.box.min.y);
  3241. bottomRight.position.set(object.box.min.x, object.box.max.y);
  3242. }
  3243. var topRight = new Circle();
  3244. topRight.radius = 4;
  3245. topRight.layer = object.layer + 1;
  3246. topRight.draggable = true;
  3247. topRight.onPointerDrag = function(pointer, viewport, delta)
  3248. {
  3249. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3250. object.box.min.copy(topRight.position);
  3251. updateHelpers();
  3252. };
  3253. object.add(topRight);
  3254. var topLeft = new Circle();
  3255. topLeft.radius = 4;
  3256. topLeft.layer = object.layer + 1;
  3257. topLeft.draggable = true;
  3258. topLeft.onPointerDrag = function(pointer, viewport, delta)
  3259. {
  3260. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3261. object.box.max.x = topLeft.position.x;
  3262. object.box.min.y = topLeft.position.y;
  3263. updateHelpers();
  3264. };
  3265. object.add(topLeft);
  3266. var bottomLeft = new Circle();
  3267. bottomLeft.radius = 4;
  3268. bottomLeft.layer = object.layer + 1;
  3269. bottomLeft.draggable = true;
  3270. bottomLeft.onPointerDrag = function(pointer, viewport, delta)
  3271. {
  3272. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3273. object.box.max.copy(bottomLeft.position);
  3274. updateHelpers();
  3275. };
  3276. object.add(bottomLeft);
  3277. var bottomRight = new Circle();
  3278. bottomRight.radius = 4;
  3279. bottomRight.layer = object.layer + 1;
  3280. bottomRight.draggable = true;
  3281. bottomRight.onPointerDrag = function(pointer, viewport, delta)
  3282. {
  3283. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3284. object.box.min.x = bottomRight.position.x;
  3285. object.box.max.y = bottomRight.position.y;
  3286. updateHelpers();
  3287. };
  3288. object.add(bottomRight);
  3289. updateHelpers();
  3290. };
  3291. exports.BezierCurve = BezierCurve;
  3292. exports.Box = Box;
  3293. exports.Box2 = Box2;
  3294. exports.BoxMask = BoxMask;
  3295. exports.Circle = Circle;
  3296. exports.DOM = DOM;
  3297. exports.EventManager = EventManager;
  3298. exports.Graph = Graph;
  3299. exports.Helpers = Helpers;
  3300. exports.Image = Image;
  3301. exports.Key = Key;
  3302. exports.Line = Line;
  3303. exports.Mask = Mask;
  3304. exports.Matrix = Matrix;
  3305. exports.MultiLineText = MultiLineText;
  3306. exports.Node = Node;
  3307. exports.NodeConnector = NodeConnector;
  3308. exports.NodeHook = NodeHook;
  3309. exports.Object2D = Object2D;
  3310. exports.Pattern = Pattern;
  3311. exports.Pointer = Pointer;
  3312. exports.QuadraticCurve = QuadraticCurve;
  3313. exports.Renderer = Renderer;
  3314. exports.Text = Text;
  3315. exports.UUID = UUID;
  3316. exports.Vector2 = Vector2;
  3317. exports.Viewport = Viewport;
  3318. exports.ViewportControls = ViewportControls;
  3319. Object.defineProperty(exports, '__esModule', { value: true });
  3320. })));