escher.js 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250
  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 (world) transform matrix.
  762. *
  763. * Used to convert pointer input points (viewport space) 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. * Check if a point in world coordinates intersects this object or its children and get a list of the objects intersected.
  843. *
  844. * @param {Vector2} point Point in world coordinates.
  845. * @param {Object2D[]} list List of objects intersected passed to children objects recursively.
  846. * @return {Object2D[]} List of object intersected by this point.
  847. */
  848. Object2D.prototype.getWorldPointIntersections = function(point, list)
  849. {
  850. if(list === undefined)
  851. {
  852. list = [];
  853. }
  854. // Calculate the pointer position in the object coordinates
  855. var localPoint = this.inverseGlobalMatrix.transformPoint(point);
  856. if(this.isInside(localPoint))
  857. {
  858. list.push(this);
  859. }
  860. // Iterate trough the children
  861. for(var i = 0; i < this.children.length; i++)
  862. {
  863. this.children[i].getWorldPointIntersections(point, list);
  864. }
  865. return list;
  866. };
  867. /**
  868. * Check if a point in world coordinates intersects this object or some of its children.
  869. *
  870. * @param {Vector2} point Point in world coordinates.
  871. * @param {boolean} recursive If set to true it will also check intersections with the object children.
  872. * @return {boolean} Returns true if the point in inside of the object.
  873. */
  874. Object2D.prototype.isWorldPointInside = function(point, recursive)
  875. {
  876. // Calculate the pointer position in the object coordinates
  877. var localPoint = this.inverseGlobalMatrix.transformPoint(point);
  878. if(this.isInside(localPoint))
  879. {
  880. return true;
  881. }
  882. // Iterate trough the children
  883. if(recursive)
  884. {
  885. for(var i = 0; i < this.children.length; i++)
  886. {
  887. if(this.children[i].isWorldPointInside(point, true))
  888. {
  889. return true;
  890. }
  891. }
  892. }
  893. return false;
  894. };
  895. /**
  896. * Destroy the object, removes it from the parent object.
  897. */
  898. Object2D.prototype.destroy = function()
  899. {
  900. if(this.parent !== null)
  901. {
  902. this.parent.remove(this);
  903. }
  904. };
  905. /**
  906. * Traverse the object tree and run a function for all objects.
  907. *
  908. * @param {Function} callback Callback function that receives the object as parameter.
  909. */
  910. Object2D.prototype.traverse = function(callback)
  911. {
  912. callback(this);
  913. for(var i = 0; i < this.children.length; i++)
  914. {
  915. this.children[i].traverse(callback);
  916. }
  917. };
  918. /**
  919. * Get a object from its children list by its UUID.
  920. *
  921. * @param {string} uuid UUID of the object to get.
  922. * @return {Object2D} The object that has the UUID specified, null if the object was not found.
  923. */
  924. Object2D.prototype.getChildByUUID = function(uuid)
  925. {
  926. var object = null;
  927. this.traverse(function(child)
  928. {
  929. if(child.uuid === uuid)
  930. {
  931. object = child;
  932. }
  933. });
  934. return object;
  935. };
  936. /**
  937. * Attach a children to this object.
  938. *
  939. * The object is set as children of this object and the transformations applied to this object are traversed to its children.
  940. *
  941. * @param {Object2D} object Object to attach to this object.
  942. */
  943. Object2D.prototype.add = function(object)
  944. {
  945. object.parent = this;
  946. object.level = this.level + 1;
  947. object.traverse(function(child)
  948. {
  949. if(child.onAdd !== null)
  950. {
  951. child.onAdd(this);
  952. }
  953. });
  954. this.children.push(object);
  955. };
  956. /**
  957. * Remove object from the children list.
  958. *
  959. * @param {Object2D} children Object to be removed.
  960. */
  961. Object2D.prototype.remove = function(children)
  962. {
  963. var index = this.children.indexOf(children);
  964. if(index !== -1)
  965. {
  966. var object = this.children[index];
  967. object.parent = null;
  968. object.level = 0;
  969. object.traverse(function(child)
  970. {
  971. if(child.onRemove !== null)
  972. {
  973. child.onRemove(this);
  974. }
  975. });
  976. this.children.splice(index, 1);
  977. }
  978. };
  979. /**
  980. * Check if a point is inside of the object. Used by the renderer check for pointer collision (required for the object to properly process pointer events).
  981. *
  982. * Point should be in local object coordinates.
  983. *
  984. * To check if a point in world coordinates intersects the object the inverseGlobalMatrix should be applied to that point before calling this method.
  985. *
  986. * @param {Vector2} point Point in local object coordinates.
  987. * @return {boolean} True if the point is inside of the object.
  988. */
  989. Object2D.prototype.isInside = function(point)
  990. {
  991. return false;
  992. };
  993. /**
  994. * Update the transformation matrix of the object.
  995. *
  996. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  997. */
  998. Object2D.prototype.updateMatrix = function(context)
  999. {
  1000. if(this.matrixAutoUpdate || this.matrixNeedsUpdate)
  1001. {
  1002. this.matrix.compose(this.position.x, this.position.y, this.scale.x, this.scale.y, this.origin.x, this.origin.y, this.rotation);
  1003. this.globalMatrix.copy(this.matrix);
  1004. if(this.parent !== null)
  1005. {
  1006. this.globalMatrix.premultiply(this.parent.globalMatrix);
  1007. }
  1008. this.inverseGlobalMatrix = this.globalMatrix.getInverse();
  1009. this.matrixNeedsUpdate = false;
  1010. }
  1011. };
  1012. /**
  1013. * Apply the transform to the rendering context, it is assumed that the viewport transform is pre-applied to the context.
  1014. *
  1015. * This is called before style() and draw(). It can also be used for some pre-rendering logic.
  1016. *
  1017. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  1018. * @param {Viewport} viewport Viewport applied to the canvas.
  1019. */
  1020. Object2D.prototype.transform = function(context, viewport)
  1021. {
  1022. this.globalMatrix.tranformContext(context);
  1023. };
  1024. /**
  1025. * 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).
  1026. *
  1027. * The draw() and style() methods can be useful for objects that share the same styling attributes but are drawing differently.
  1028. *
  1029. * Should be implemented by underlying classes.
  1030. *
  1031. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  1032. * @param {Viewport} viewport Viewport used to view the canvas content.
  1033. * @param {DOM} canvas DOM canvas element where the content is being drawn.
  1034. */
  1035. Object2D.prototype.style = null; // function(context, viewport, canvas){};
  1036. /**
  1037. * Draw the object into the canvas, this is called transform() and style(), should be where the content is actually drawn into the canvas.
  1038. *
  1039. * Should be implemented by underlying classes.
  1040. *
  1041. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  1042. * @param {Viewport} viewport Viewport used to view the canvas content.
  1043. * @param {DOM} canvas DOM canvas element where the content is being drawn.
  1044. */
  1045. Object2D.prototype.draw = null; // function(context, viewport, canvas){};
  1046. /**
  1047. * Callback method while the object is being dragged across the screen.
  1048. *
  1049. * By default is adds the delta value to the object position (making it follow the mouse movement).
  1050. *
  1051. * Delta is the movement of the pointer already translated into local object coordinates.
  1052. *
  1053. * To detect when the object drag stops the onPointerDragEnd() method can be used.
  1054. *
  1055. * @param {Pointer} pointer Pointer object that receives the user input.
  1056. * @param {Viewport} viewport Viewport where the object is drawn.
  1057. * @param {Vector2} delta Pointer movement diff in world space since the last frame.
  1058. * @param {Vector2} positionWorld Position of the dragging pointer in world coordinates.
  1059. */
  1060. Object2D.prototype.onPointerDrag = function(pointer, viewport, delta, positionWorld)
  1061. {
  1062. this.position.add(delta);
  1063. };
  1064. /**
  1065. * Callback method called when the pointer drag start after the button was pressed
  1066. *
  1067. * @param {Pointer} pointer Pointer object that receives the user input.
  1068. * @param {Viewport} viewport Viewport where the object is drawn.
  1069. */
  1070. Object2D.prototype.onPointerDragStart = null;
  1071. /**
  1072. * Callback method called when the pointer drag ends after the button has been released.
  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.onPointerDragEnd = null;
  1078. /**
  1079. * Method called when the object its added to a parent.
  1080. *
  1081. * @param {Object2D} parent Parent object were it was added.
  1082. */
  1083. Object2D.prototype.onAdd = null;
  1084. /**
  1085. * Method called when the object gets removed from its parent
  1086. *
  1087. * @param {Object2D} parent Parent object from were the object is being removed.
  1088. */
  1089. Object2D.prototype.onRemove = null;
  1090. /**
  1091. * Callback method called every time before the object is draw into the canvas.
  1092. *
  1093. * Should be used to run object logic, any preparation code, move the object, etc.
  1094. *
  1095. * This method is called for every object before rendering.
  1096. */
  1097. Object2D.prototype.onUpdate = null;
  1098. /**
  1099. * Callback method called when the pointer enters the object.
  1100. *
  1101. * It is not called while the pointer is inside of the object, just on the first time that the pointer enters the object for that use onPointerOver()
  1102. *
  1103. * @param {Pointer} pointer Pointer object that receives the user input.
  1104. * @param {Viewport} viewport Viewport where the object is drawn.
  1105. */
  1106. Object2D.prototype.onPointerEnter = null;
  1107. /**
  1108. * Method called when the was inside of the object and leaves the object.
  1109. *
  1110. * @param {Pointer} pointer Pointer object that receives the user input.
  1111. * @param {Viewport} viewport Viewport where the object is drawn.
  1112. */
  1113. Object2D.prototype.onPointerLeave = null;
  1114. /**
  1115. * Method while the pointer is over (inside) of the object.
  1116. *
  1117. * @param {Pointer} pointer Pointer object that receives the user input.
  1118. * @param {Viewport} viewport Viewport where the object is drawn.
  1119. */
  1120. Object2D.prototype.onPointerOver = null;
  1121. /**
  1122. * Method called while the pointer button is pressed.
  1123. *
  1124. * @param {Pointer} pointer Pointer object that receives the user input.
  1125. * @param {Viewport} viewport Viewport where the object is drawn.
  1126. */
  1127. Object2D.prototype.onButtonPressed = null;
  1128. /**
  1129. * Method called while the pointer button is double clicked.
  1130. *
  1131. * @param {Pointer} pointer Pointer object that receives the user input.
  1132. * @param {Viewport} viewport Viewport where the object is drawn.
  1133. */
  1134. Object2D.prototype.onDoubleClick = null;
  1135. /**
  1136. * Callback method called when the pointer button is pressed down (single time).
  1137. *
  1138. * @param {Pointer} pointer Pointer object that receives the user input.
  1139. * @param {Viewport} viewport Viewport where the object is drawn.
  1140. */
  1141. Object2D.prototype.onButtonDown = null;
  1142. /**
  1143. * Method called when the pointer button is released (single time).
  1144. *
  1145. * @param {Pointer} pointer Pointer object that receives the user input.
  1146. * @param {Viewport} viewport Viewport where the object is drawn.
  1147. */
  1148. Object2D.prototype.onButtonUp = null;
  1149. /**
  1150. * Text element, used to draw single line text into the canvas.
  1151. *
  1152. * For multi line text with support for line break check {MultiLineText} object.
  1153. *
  1154. * @class
  1155. * @extends {Object2D}
  1156. */
  1157. function Text()
  1158. {
  1159. Object2D.call(this);
  1160. /**
  1161. * Text value displayed by this element.
  1162. *
  1163. * @type {string}
  1164. */
  1165. this.text = "";
  1166. /**
  1167. * Font of the text.
  1168. *
  1169. * @type {string}
  1170. */
  1171. this.font = "16px Arial";
  1172. /**
  1173. * Style of the object border line. If set null it is ignored.
  1174. *
  1175. * @type {string}
  1176. */
  1177. this.strokeStyle = null;
  1178. /**
  1179. * Line width, only used if a valid strokeStyle is defined.
  1180. *
  1181. * @type {number}
  1182. */
  1183. this.lineWidth = 1;
  1184. /**
  1185. * CSS background color of the box. If set null it is ignored.
  1186. *
  1187. * @type {string}
  1188. */
  1189. this.fillStyle = "#000000";
  1190. /**
  1191. * Text align property. Same values as used for canvas text applies
  1192. *
  1193. * Check documentation at https://developer.mozilla.org/en-US/docs/Web/CSS/text-align for mode details about this property.
  1194. *
  1195. * @type {string}
  1196. */
  1197. this.textAlign = "center";
  1198. /**
  1199. * Text baseline defines the vertical position of the text relative to the imaginary line Y position. Same values as used for canvas text applies
  1200. *
  1201. * Check documentation at https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textBaseline for mode details about this property.
  1202. *
  1203. * @type {string}
  1204. */
  1205. this.textBaseline = "middle";
  1206. }
  1207. Text.prototype = Object.create(Object2D.prototype);
  1208. Text.prototype.draw = function(context, viewport, canvas)
  1209. {
  1210. context.font = this.font;
  1211. context.textAlign = this.textAlign;
  1212. context.textBaseline = this.textBaseline ;
  1213. if(this.fillStyle !== null)
  1214. {
  1215. context.fillStyle = this.fillStyle;
  1216. context.fillText(this.text, 0, 0);
  1217. }
  1218. if(this.strokeStyle !== null)
  1219. {
  1220. context.strokeStyle = this.strokeStyle;
  1221. context.strokeText(this.text, 0, 0);
  1222. }
  1223. };
  1224. /**
  1225. * Multiple line text drawing directly into the canvas.
  1226. *
  1227. * Has support for basic text indent and alignment.
  1228. *
  1229. * @class
  1230. * @extends {Text}
  1231. */
  1232. function MultiLineText()
  1233. {
  1234. Text.call(this);
  1235. /**
  1236. * Maximum width of the text content. After text reaches the max width a line break is placed.
  1237. *
  1238. * Can be set to null to be ignored.
  1239. *
  1240. * @type {number}
  1241. */
  1242. this.maxWidth = null;
  1243. /**
  1244. * Height of each line of text, can be smaller or larger than the actual font size.
  1245. *
  1246. * Can be set to null to be ignored.
  1247. *
  1248. * @type {number}
  1249. */
  1250. this.lineHeight = null;
  1251. }
  1252. MultiLineText.prototype = Object.create(Text.prototype);
  1253. MultiLineText.prototype.draw = function(context, viewport, canvas)
  1254. {
  1255. context.font = this.font;
  1256. context.textAlign = this.textAlign;
  1257. context.textBaseline = this.textBaseline;
  1258. var lineHeight = this.lineHeight || Number.parseFloat(this.font);
  1259. var lines = this.text.split("\n");
  1260. var offsetY = 0;
  1261. // Iterate trough all lines (breakpoints)
  1262. for(var i = 0; i < lines.length; i++)
  1263. {
  1264. var line = lines[i];
  1265. var size = context.measureText(line);
  1266. var sublines = [];
  1267. // Split into multiple sub-lines
  1268. if(this.maxWidth !== null && size.width > this.maxWidth)
  1269. {
  1270. while(line.length > 0)
  1271. {
  1272. var subline = "";
  1273. var subsize = context.measureText(subline + line[0]);
  1274. while(subsize.width < this.maxWidth && line.length > 0)
  1275. {
  1276. subline += line[0];
  1277. line = line.substr(1);
  1278. subsize = context.measureText(subline + line[0]);
  1279. }
  1280. sublines.push(subline);
  1281. }
  1282. }
  1283. // Fits into a single line
  1284. else
  1285. {
  1286. sublines = [line];
  1287. }
  1288. for(var j = 0; j < sublines.length; j++)
  1289. {
  1290. if(this.fillStyle !== null)
  1291. {
  1292. context.fillStyle = this.fillStyle;
  1293. context.fillText(sublines[j], this.position.x, this.position.y + offsetY);
  1294. }
  1295. if(this.strokeStyle !== null)
  1296. {
  1297. context.strokeStyle = this.strokeStyle;
  1298. context.strokeText(sublines[j], this.position.x, this.position.y + offsetY);
  1299. }
  1300. offsetY += lineHeight;
  1301. }
  1302. }
  1303. };
  1304. /**
  1305. * EventManager is used to manager DOM events creating and destruction in a single function call.
  1306. *
  1307. * It is used by objects to make it easier to add and remove events from global DOM objects.
  1308. *
  1309. * @class
  1310. */
  1311. function EventManager()
  1312. {
  1313. /**
  1314. * Stores all events in the manager, their target and callback.
  1315. *
  1316. * Format [target, event, callback, active]
  1317. *
  1318. * @type {Array}
  1319. */
  1320. this.events = [];
  1321. }
  1322. /**
  1323. * Add new event to the manager.
  1324. *
  1325. * @param {Element} target Event target element.
  1326. * @param {String} event Event name.
  1327. * @param {Function} callback Callback function.
  1328. */
  1329. EventManager.prototype.add = function(target, event, callback)
  1330. {
  1331. this.events.push([target, event, callback, false]);
  1332. };
  1333. /**
  1334. * Destroys this manager and remove all events.
  1335. */
  1336. EventManager.prototype.clear = function()
  1337. {
  1338. this.destroy();
  1339. this.events = [];
  1340. };
  1341. /**
  1342. * Creates all events in this manager.
  1343. */
  1344. EventManager.prototype.create = function()
  1345. {
  1346. for(var i = 0; i < this.events.length; i++)
  1347. {
  1348. var event = this.events[i];
  1349. event[0].addEventListener(event[1], event[2]);
  1350. event[3] = true;
  1351. }
  1352. };
  1353. /**
  1354. * Removes all events in this manager.
  1355. */
  1356. EventManager.prototype.destroy = function()
  1357. {
  1358. for(var i = 0; i < this.events.length; i++)
  1359. {
  1360. var event = this.events[i];
  1361. event[0].removeEventListener(event[1], event[2]);
  1362. event[3] = false;
  1363. }
  1364. };
  1365. /**
  1366. * Key is used by Keyboard, Pointer, etc, to represent a key state.
  1367. *
  1368. * @class
  1369. */
  1370. function Key()
  1371. {
  1372. /**
  1373. * Indicates if this key is currently pressed.
  1374. */
  1375. this.pressed = false;
  1376. /**
  1377. * Indicates if this key was just pressed.
  1378. */
  1379. this.justPressed = false;
  1380. /**
  1381. * Indicates if this key was just released.
  1382. */
  1383. this.justReleased = false;
  1384. }
  1385. Key.DOWN = -1;
  1386. Key.UP = 1;
  1387. Key.RESET = 0;
  1388. Key.prototype.constructor = Key;
  1389. /**
  1390. * Update Key status based on new key state.
  1391. */
  1392. Key.prototype.update = function(action)
  1393. {
  1394. this.justPressed = false;
  1395. this.justReleased = false;
  1396. if(action === Key.DOWN)
  1397. {
  1398. if(this.pressed === false)
  1399. {
  1400. this.justPressed = true;
  1401. }
  1402. this.pressed = true;
  1403. }
  1404. else if(action === Key.UP)
  1405. {
  1406. if(this.pressed)
  1407. {
  1408. this.justReleased = true;
  1409. }
  1410. this.pressed = false;
  1411. }
  1412. else if(action === Key.RESET)
  1413. {
  1414. this.justReleased = false;
  1415. this.justPressed = false;
  1416. }
  1417. };
  1418. /**
  1419. * Set this key attributes manually.
  1420. */
  1421. Key.prototype.set = function(justPressed, pressed, justReleased)
  1422. {
  1423. this.justPressed = justPressed;
  1424. this.pressed = pressed;
  1425. this.justReleased = justReleased;
  1426. };
  1427. /**
  1428. * Reset key to default values.
  1429. */
  1430. Key.prototype.reset = function()
  1431. {
  1432. this.justPressed = false;
  1433. this.pressed = false;
  1434. this.justReleased = false;
  1435. };
  1436. /**
  1437. * Pointer object is used to called input from the user, works for booth mouse or touch screens.
  1438. *
  1439. * It is responsible for synchronizing user input with the render of the graphics.
  1440. *
  1441. * @class
  1442. * @param {Element} domElement DOM element to create the pointer events.
  1443. * @param {Element} canvas Canvas DOM element where the content is being drawn.
  1444. */
  1445. function Pointer(domElement, canvas)
  1446. {
  1447. //Raw data
  1448. this._keys = new Array(5);
  1449. this._position = new Vector2(0, 0);
  1450. this._positionUpdated = false;
  1451. this._delta = new Vector2(0, 0);
  1452. this._wheel = 0;
  1453. this._wheelUpdated = false;
  1454. this._doubleClicked = new Array(5);
  1455. /**
  1456. * Array with pointer buttons status.
  1457. */
  1458. this.keys = new Array(5);
  1459. /**
  1460. * Pointer position inside of the window (coordinates in window space).
  1461. */
  1462. this.position = new Vector2(0, 0);
  1463. /**
  1464. * Pointer movement (coordinates in window space).
  1465. */
  1466. this.delta = new Vector2(0, 0);
  1467. /**
  1468. * Pointer scroll wheel movement.
  1469. */
  1470. this.wheel = 0;
  1471. /**
  1472. * Indicates a button of the pointer was double clicked.
  1473. */
  1474. this.doubleClicked = new Array(5);
  1475. /**
  1476. * DOM element where to attach the pointer events.
  1477. */
  1478. this.domElement = (domElement !== undefined) ? domElement : window;
  1479. /**
  1480. * Canvas attached to this pointer instance used to calculate position and delta in element space coordinates.
  1481. */
  1482. this.canvas = null;
  1483. if(canvas !== undefined)
  1484. {
  1485. this.setCanvas(canvas);
  1486. }
  1487. /**
  1488. * Event manager responsible for updating the raw data variables.
  1489. *
  1490. * Diferent events are used depending on the host platform.
  1491. *
  1492. * When the update method is called the raw data is reset.
  1493. */
  1494. this.events = new EventManager();
  1495. //Initialize key instances
  1496. for(var i = 0; i < 5; i++)
  1497. {
  1498. this._doubleClicked[i] = false;
  1499. this.doubleClicked[i] = false;
  1500. this._keys[i] = new Key();
  1501. this.keys[i] = new Key();
  1502. }
  1503. //Self pointer
  1504. var self = this;
  1505. //Scroll wheel
  1506. if(window.onmousewheel !== undefined)
  1507. {
  1508. //Chrome, edge
  1509. this.events.add(this.domElement, "mousewheel", function(event)
  1510. {
  1511. self._wheel = event.deltaY;
  1512. self._wheelUpdated = true;
  1513. });
  1514. }
  1515. else if(window.addEventListener !== undefined)
  1516. {
  1517. //Firefox
  1518. this.events.add(this.domElement, "DOMMouseScroll", function(event)
  1519. {
  1520. self._wheel = event.detail * 30;
  1521. self._wheelUpdated = true;
  1522. });
  1523. }
  1524. else
  1525. {
  1526. this.events.add(this.domElement, "wheel", function(event)
  1527. {
  1528. self._wheel = event.deltaY;
  1529. self._wheelUpdated = true;
  1530. });
  1531. }
  1532. //Touchscreen input events
  1533. if(window.ontouchstart !== undefined || navigator.msMaxTouchPoints > 0)
  1534. {
  1535. //Auxiliar variables to calculate touch delta
  1536. var lastTouch = new Vector2(0, 0);
  1537. //Touch start event
  1538. this.events.add(this.domElement, "touchstart", function(event)
  1539. {
  1540. var touch = event.touches[0];
  1541. self.updatePosition(touch.clientX, touch.clientY, 0, 0);
  1542. self.updateKey(Pointer.LEFT, Key.DOWN);
  1543. lastTouch.set(touch.clientX, touch.clientY);
  1544. });
  1545. //Touch end event
  1546. this.events.add(this.domElement, "touchend", function(event)
  1547. {
  1548. self.updateKey(Pointer.LEFT, Key.UP);
  1549. });
  1550. //Touch cancel event
  1551. this.events.add(this.domElement, "touchcancel", function(event)
  1552. {
  1553. self.updateKey(Pointer.LEFT, Key.UP);
  1554. });
  1555. //Touch move event
  1556. this.events.add(document.body, "touchmove", function(event)
  1557. {
  1558. var touch = event.touches[0];
  1559. self.updatePosition(touch.clientX, touch.clientY, touch.clientX - lastTouch.x, touch.clientY - lastTouch.y);
  1560. lastTouch.set(touch.clientX, touch.clientY);
  1561. });
  1562. }
  1563. //Move
  1564. this.events.add(this.domElement, "mousemove", function(event)
  1565. {
  1566. self.updatePosition(event.clientX, event.clientY, event.movementX, event.movementY);
  1567. });
  1568. //Button pressed
  1569. this.events.add(this.domElement, "mousedown", function(event)
  1570. {
  1571. self.updateKey(event.which - 1, Key.DOWN);
  1572. });
  1573. //Button released
  1574. this.events.add(this.domElement, "mouseup", function(event)
  1575. {
  1576. self.updateKey(event.which - 1, Key.UP);
  1577. });
  1578. //Drag start
  1579. this.events.add(this.domElement, "dragstart", function(event)
  1580. {
  1581. self.updateKey(event.which - 1, Key.UP);
  1582. });
  1583. //Pointer double click
  1584. this.events.add(this.domElement, "dblclick", function(event)
  1585. {
  1586. self._doubleClicked[event.which - 1] = true;
  1587. });
  1588. this.create();
  1589. }
  1590. Pointer.prototype = Pointer;
  1591. Pointer.prototype.constructor = Pointer;
  1592. /**
  1593. * Left pointer button.
  1594. */
  1595. Pointer.LEFT = 0;
  1596. /**
  1597. * Middle pointer button.
  1598. */
  1599. Pointer.MIDDLE = 1;
  1600. /**
  1601. * Right pointer button.
  1602. */
  1603. Pointer.RIGHT = 2;
  1604. /**
  1605. * Back pointer navigation button.
  1606. */
  1607. Pointer.BACK = 3;
  1608. /**
  1609. * Forward pointer navigation button.
  1610. */
  1611. Pointer.FORWARD = 4;
  1612. /**
  1613. * Element to be used for coordinates calculation relative to that canvas.
  1614. *
  1615. * @param {DOM} canvas Canvas to be attached to the Pointer instance
  1616. */
  1617. Pointer.setCanvas = function(element)
  1618. {
  1619. this.canvas = element;
  1620. element.pointerInside = false;
  1621. element.addEventListener("mouseenter", function()
  1622. {
  1623. this.pointerInside = true;
  1624. });
  1625. element.addEventListener("mouseleave", function()
  1626. {
  1627. this.pointerInside = false;
  1628. });
  1629. };
  1630. /**
  1631. * Check if pointer is inside attached canvas (updated async).
  1632. *
  1633. * @return {boolean} True if pointer is currently inside the canvas
  1634. */
  1635. Pointer.insideCanvas = function()
  1636. {
  1637. return this.canvas !== null && this.canvas.pointerInside;
  1638. };
  1639. /**
  1640. * Check if pointer button is currently pressed.
  1641. *
  1642. * @param {Number} button Button to check status of
  1643. * @return {boolean} True if button is currently pressed
  1644. */
  1645. Pointer.buttonPressed = function(button)
  1646. {
  1647. return this.keys[button].pressed;
  1648. };
  1649. /**
  1650. * Check if pointer button was double clicked.
  1651. *
  1652. * @param {Number} button Button to check status of
  1653. * @return {boolean} True if some pointer button was just double clicked
  1654. */
  1655. Pointer.buttonDoubleClicked = function(button)
  1656. {
  1657. return this.doubleClicked[button];
  1658. };
  1659. /**
  1660. * Check if a pointer button was just pressed.
  1661. *
  1662. * @param {Number} button Button to check status of
  1663. * @return {boolean} True if button was just pressed
  1664. */
  1665. Pointer.buttonJustPressed = function(button)
  1666. {
  1667. return this.keys[button].justPressed;
  1668. };
  1669. /**
  1670. * Check if a pointer button was just released.
  1671. *
  1672. * @param {Number} button Button to check status of
  1673. * @return {boolean} True if button was just released
  1674. */
  1675. Pointer.buttonJustReleased = function(button)
  1676. {
  1677. return this.keys[button].justReleased;
  1678. };
  1679. /**
  1680. * Update pointer position.
  1681. *
  1682. * Automatically called by the runtime.
  1683. *
  1684. * @param {Number} x
  1685. * @param {Number} y
  1686. * @param {Number} xDiff
  1687. * @param {Number} yDiff
  1688. */
  1689. Pointer.updatePosition = function(x, y, xDiff, yDiff)
  1690. {
  1691. if(this.canvas !== null)
  1692. {
  1693. var rect = this.canvas.getBoundingClientRect();
  1694. x -= rect.left;
  1695. y -= rect.top;
  1696. }
  1697. this._position.set(x, y);
  1698. this._delta.x += xDiff;
  1699. this._delta.y += yDiff;
  1700. this._positionUpdated = true;
  1701. };
  1702. /**
  1703. * Update a pointer button.
  1704. *
  1705. * Automatically called by the runtime.
  1706. *
  1707. * @param {Number} button
  1708. * @param {Number} action
  1709. */
  1710. Pointer.updateKey = function(button, action)
  1711. {
  1712. if(button > -1)
  1713. {
  1714. this._keys[button].update(action);
  1715. }
  1716. };
  1717. /**
  1718. * Update pointer buttons state, position, wheel and delta synchronously.
  1719. */
  1720. Pointer.update = function()
  1721. {
  1722. //Update pointer keys state
  1723. for(var i = 0; i < 5; i++)
  1724. {
  1725. if(this._keys[i].justPressed && this.keys[i].justPressed)
  1726. {
  1727. this._keys[i].justPressed = false;
  1728. }
  1729. if(this._keys[i].justReleased && this.keys[i].justReleased)
  1730. {
  1731. this._keys[i].justReleased = false;
  1732. }
  1733. this.keys[i].set(this._keys[i].justPressed, this._keys[i].pressed, this._keys[i].justReleased);
  1734. //Update pointer double click
  1735. if(this._doubleClicked[i] === true)
  1736. {
  1737. this.doubleClicked[i] = true;
  1738. this._doubleClicked[i] = false;
  1739. }
  1740. else
  1741. {
  1742. this.doubleClicked[i] = false;
  1743. }
  1744. }
  1745. //Update pointer wheel
  1746. if(this._wheelUpdated)
  1747. {
  1748. this.wheel = this._wheel;
  1749. this._wheelUpdated = false;
  1750. }
  1751. else
  1752. {
  1753. this.wheel = 0;
  1754. }
  1755. //Update pointer Position if needed
  1756. if(this._positionUpdated)
  1757. {
  1758. this.delta.copy(this._delta);
  1759. this.position.copy(this._position);
  1760. this._delta.set(0,0);
  1761. this._positionUpdated = false;
  1762. }
  1763. else
  1764. {
  1765. this.delta.x = 0;
  1766. this.delta.y = 0;
  1767. }
  1768. };
  1769. /**
  1770. * Create pointer events.
  1771. */
  1772. Pointer.create = function()
  1773. {
  1774. this.events.create();
  1775. };
  1776. /**
  1777. * Dispose pointer events.
  1778. */
  1779. Pointer.dispose = function()
  1780. {
  1781. this.events.destroy();
  1782. };
  1783. /**
  1784. * 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.
  1785. *
  1786. * The viewport can be moved, rotated and scaled to navigate the virtual canvas.
  1787. *
  1788. * @class
  1789. * @param {Element} canvas Canvas DOM element where the viewport is being rendered.
  1790. */
  1791. function Viewport(canvas)
  1792. {
  1793. /**
  1794. * UUID of the object.
  1795. */
  1796. this.uuid = UUID.generate();
  1797. /**
  1798. * Canvas DOM element where the viewport is being rendered.
  1799. */
  1800. this.canvas = canvas;
  1801. /**
  1802. * Position of the object.
  1803. */
  1804. this.position = new Vector2(0, 0);
  1805. /**
  1806. * Scale of the object.
  1807. */
  1808. this.scale = 1.0;
  1809. /**
  1810. * Rotation of the object relative to its center.
  1811. */
  1812. this.rotation = 0.0;
  1813. /**
  1814. * Local transformation matrix applied to the object.
  1815. */
  1816. this.matrix = new Matrix();
  1817. /**
  1818. * Inverse of the local transformation matrix.
  1819. */
  1820. this.inverseMatrix = new Matrix();
  1821. /**
  1822. * If true the matrix is updated before rendering the object.
  1823. */
  1824. this.matrixNeedsUpdate = true;
  1825. /**
  1826. * Flag to indicate if the viewport should move when scaling.
  1827. *
  1828. * For some application its easier to focus the target if the viewport moves to the pointer location while scaling.
  1829. */
  1830. this.moveOnScale = false;
  1831. /**
  1832. * Value of the initial point of rotation if the viewport is being rotated.
  1833. *
  1834. * Is set to null when the viewport is not being rotated.
  1835. */
  1836. this.rotationPoint = null;
  1837. }
  1838. /**
  1839. * Calculate and update the viewport transformation matrix.
  1840. *
  1841. * Also updates the inverse matrix of the viewport.
  1842. */
  1843. Viewport.prototype.updateMatrix = function()
  1844. {
  1845. if(this.matrixNeedsUpdate)
  1846. {
  1847. this.matrix.m = [1, 0, 0, 1, this.position.x, this.position.y];
  1848. if(this.rotation !== 0)
  1849. {
  1850. var c = Math.cos(this.rotation);
  1851. var s = Math.sin(this.rotation);
  1852. this.matrix.multiply(new Matrix([c, s, -s, c, 0, 0]));
  1853. }
  1854. if(this.scale !== 1)
  1855. {
  1856. this.matrix.scale(this.scale, this.scale);
  1857. }
  1858. this.inverseMatrix = this.matrix.getInverse();
  1859. this.matrixNeedsUpdate = false;
  1860. }
  1861. };
  1862. /**
  1863. * Center the viewport relative to a object.
  1864. *
  1865. * The position of the object is used a central point, this method does not consider "box" attributes or other strucures in the object.
  1866. *
  1867. * @param {Object2D} object Object to be centered on the viewport.
  1868. * @param {Element} canvas Canvas element where the image is drawn.
  1869. */
  1870. Viewport.prototype.centerObject = function(object, canvas)
  1871. {
  1872. var position = object.globalMatrix.transformPoint(new Vector2());
  1873. position.multiplyScalar(-this.scale);
  1874. position.x += canvas.width / 2;
  1875. position.y += canvas.height / 2;
  1876. this.position.copy(position);
  1877. this.matrixNeedsUpdate = true;
  1878. };
  1879. /**
  1880. * Viewport controls are used to allow the user to control the viewport.
  1881. *
  1882. * @class
  1883. * @param {Viewport} viewport
  1884. */
  1885. function ViewportControls(viewport)
  1886. {
  1887. /**
  1888. * Viewport being controlled by this object.
  1889. */
  1890. this.viewport = viewport;
  1891. /**
  1892. * Button used to drag and viewport around.
  1893. *
  1894. * On touch enabled devices the touch event is represented as a LEFT button.
  1895. */
  1896. this.dragButton = Pointer.RIGHT;
  1897. /**
  1898. * Is set to true allow the viewport to be scalled.
  1899. *
  1900. * Scaling is performed using the pointer scroll.
  1901. */
  1902. this.allowScale = true;
  1903. /**
  1904. * Flag to indicate if the viewport should move when scalling.
  1905. *
  1906. * For some application its easier to focus the target if the viewport moves to the pointer location while scalling.
  1907. */
  1908. this.moveOnScale = false;
  1909. /**
  1910. * If true allows the viewport to be rotated.
  1911. *
  1912. * Rotation is performed by holding the RIGHT and LEFT pointer buttons and rotating around the initial point.
  1913. */
  1914. this.allowRotation = true;
  1915. /**
  1916. * Value of the initial point of rotation if the viewport is being rotated.
  1917. *
  1918. * Is set to null when the viewport is not being rotated.
  1919. */
  1920. this.rotationPoint = null;
  1921. /**
  1922. * Initial rotation of the viewport.
  1923. */
  1924. this.rotationInitial = 0;
  1925. }
  1926. /**
  1927. * Update the viewport controls using the pointer object.
  1928. *
  1929. * Should be called every frame before rendering.
  1930. *
  1931. * @param {Pointer} pointer
  1932. */
  1933. ViewportControls.prototype.update = function(pointer)
  1934. {
  1935. // Scale
  1936. if(this.allowScale && pointer.wheel !== 0)
  1937. {
  1938. var scale = pointer.wheel * 1e-3 * this.viewport.scale;
  1939. this.viewport.scale -= scale;
  1940. this.viewport.matrixNeedsUpdate = true;
  1941. // Move on scale
  1942. if(this.moveOnScale && pointer.canvas !== null)
  1943. {
  1944. this.viewport.updateMatrix();
  1945. var pointerWorld = this.viewport.inverseMatrix.transformPoint(pointer.position);
  1946. var centerWorld = new Vector2(pointer.canvas.width / 2.0, pointer.canvas.height / 2.0);
  1947. centerWorld = this.viewport.inverseMatrix.transformPoint(centerWorld);
  1948. var delta = pointerWorld.clone();
  1949. delta.sub(centerWorld);
  1950. delta.multiplyScalar(0.1);
  1951. this.viewport.position.sub(delta);
  1952. this.viewport.matrixNeedsUpdate = true;
  1953. }
  1954. }
  1955. // Rotation
  1956. if(this.allowRotation && pointer.buttonPressed(Pointer.RIGHT) && pointer.buttonPressed(Pointer.LEFT))
  1957. {
  1958. // Rotation pivot
  1959. if(this.rotationPoint === null)
  1960. {
  1961. this.rotationPoint = pointer.position.clone();
  1962. this.rotationInitial = this.viewport.rotation;
  1963. }
  1964. else
  1965. {
  1966. var pointer = pointer.position.clone();
  1967. pointer.sub(this.rotationPoint);
  1968. this.viewport.rotation = this.rotationInitial + pointer.angle();
  1969. this.viewport.matrixNeedsUpdate = true;
  1970. }
  1971. }
  1972. // Drag
  1973. else
  1974. {
  1975. this.rotationPoint = null;
  1976. if(pointer.buttonPressed(this.dragButton))
  1977. {
  1978. this.viewport.position.x += pointer.delta.x;
  1979. this.viewport.position.y += pointer.delta.y;
  1980. this.viewport.matrixNeedsUpdate = true;
  1981. }
  1982. }
  1983. };
  1984. /**
  1985. * The renderer is responsible for drawing the objects structure into the canvas element and manage its rendering state.
  1986. *
  1987. * @class
  1988. * @param {Element} canvas Canvas to render the content.
  1989. * @param {Object} options Renderer canvas options.
  1990. */
  1991. function Renderer(canvas, options)
  1992. {
  1993. if(options === undefined)
  1994. {
  1995. options =
  1996. {
  1997. alpha: true
  1998. };
  1999. }
  2000. /**
  2001. * Canvas DOM element, has to be managed by the user.
  2002. */
  2003. this.canvas = canvas;
  2004. /**
  2005. * Canvas 2D rendering context used to draw content.
  2006. */
  2007. this.context = canvas.getContext("2d", {alpha: options.alpha});
  2008. this.context.imageSmoothingEnabled = true;
  2009. this.context.globalCompositeOperation = "source-over";
  2010. /**
  2011. * Pointer input handler object.
  2012. */
  2013. this.pointer = new Pointer(window, canvas);
  2014. /**
  2015. * Indicates if the canvas should be automatically cleared before new frame is drawn.
  2016. *
  2017. * If set to false the user should clear the frame before drawing.
  2018. */
  2019. this.autoClear = true;
  2020. }
  2021. /**
  2022. * Creates a infinite render loop to render the group into a viewport each frame.
  2023. *
  2024. * The render loop cannot be destroyed, and it automatically creates a viewport controls object.
  2025. *
  2026. * @param {Object2D} group Group to be rendered.
  2027. * @param {Viewport} viewport Viewport into the objects.
  2028. * @param {Function} onUpdate Function called before rendering the frame.
  2029. */
  2030. Renderer.prototype.createRenderLoop = function(group, viewport, onUpdate)
  2031. {
  2032. var self = this;
  2033. var controls = new ViewportControls(viewport);
  2034. function loop()
  2035. {
  2036. if(onUpdate !== undefined)
  2037. {
  2038. onUpdate();
  2039. }
  2040. controls.update(self.pointer);
  2041. self.update(group, viewport);
  2042. requestAnimationFrame(loop);
  2043. }
  2044. loop();
  2045. };
  2046. /**
  2047. * Renders a object using a user defined viewport into a canvas element.
  2048. *
  2049. * Before rendering automatically updates the input handlers and calculates the objects/viewport transformation matrices.
  2050. *
  2051. * The canvas state is saved and restored for each individual object, ensuring that the code of one object does not affect another one.
  2052. *
  2053. * 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.
  2054. *
  2055. * @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.
  2056. * @param viewport {Viewport} Viewport to be updated (should be the one where the objects will be rendered after).
  2057. */
  2058. Renderer.prototype.update = function(object, viewport)
  2059. {
  2060. // Get objects to be rendered
  2061. var objects = [];
  2062. // Traverse object and get all objects into a list.
  2063. object.traverse(function(child)
  2064. {
  2065. if(child.visible)
  2066. {
  2067. objects.push(child);
  2068. }
  2069. });
  2070. // Sort objects by layer
  2071. objects.sort(function(a, b)
  2072. {
  2073. if(b.layer === a.layer)
  2074. {
  2075. return b.level - a.level;
  2076. }
  2077. return b.layer - a.layer;
  2078. });
  2079. // Pointer object update
  2080. var pointer = this.pointer;
  2081. pointer.update();
  2082. // Viewport transform matrix
  2083. viewport.updateMatrix();
  2084. // Project pointer coordinates
  2085. var point = pointer.position.clone();
  2086. var viewportPoint = viewport.inverseMatrix.transformPoint(point);
  2087. // Object pointer events
  2088. for(var i = 0; i < objects.length; i++)
  2089. {
  2090. var child = objects[i];
  2091. //Process the object pointer events
  2092. if(child.pointerEvents)
  2093. {
  2094. // Calculate the pointer position in the object coordinates
  2095. var localPoint = child.inverseGlobalMatrix.transformPoint(child.ignoreViewport ? point : viewportPoint);
  2096. // Check if the pointer pointer is inside
  2097. if(child.isInside(localPoint))
  2098. {
  2099. // Pointer enter
  2100. if(!child.pointerInside && child.onPointerEnter !== null)
  2101. {
  2102. child.onPointerEnter(pointer, viewport);
  2103. }
  2104. // Pointer over
  2105. if(child.onPointerOver !== null)
  2106. {
  2107. child.onPointerOver(pointer, viewport);
  2108. }
  2109. // Double click
  2110. if(pointer.buttonDoubleClicked(Pointer.LEFT) && child.onDoubleClick !== null)
  2111. {
  2112. child.onDoubleClick(pointer, viewport);
  2113. }
  2114. // Pointer pressed
  2115. if(pointer.buttonPressed(Pointer.LEFT) && child.onButtonPressed !== null)
  2116. {
  2117. child.onButtonPressed(pointer, viewport);
  2118. }
  2119. // Just released
  2120. if(pointer.buttonJustReleased(Pointer.LEFT) && child.onButtonUp !== null)
  2121. {
  2122. child.onButtonUp(pointer, viewport);
  2123. }
  2124. // Pointer just pressed
  2125. if(pointer.buttonJustPressed(Pointer.LEFT))
  2126. {
  2127. if(child.onButtonDown !== null)
  2128. {
  2129. child.onButtonDown(pointer, viewport);
  2130. }
  2131. // Drag object and break to only start a drag operation on the top element.
  2132. if(child.draggable)
  2133. {
  2134. child.beingDragged = true;
  2135. if(child.onPointerDragStart !== null)
  2136. {
  2137. child.onPointerDragStart(pointer, viewport);
  2138. }
  2139. break;
  2140. }
  2141. }
  2142. child.pointerInside = true;
  2143. }
  2144. else if(child.pointerInside)
  2145. {
  2146. // Pointer leave
  2147. if(child.onPointerLeave !== null)
  2148. {
  2149. child.onPointerLeave(pointer, viewport);
  2150. }
  2151. child.pointerInside = false;
  2152. }
  2153. // Stop object drag
  2154. if(pointer.buttonJustReleased(Pointer.LEFT))
  2155. {
  2156. if(child.draggable)
  2157. {
  2158. // On drag end callback
  2159. if(child.beingDragged === true && child.onPointerDragEnd !== null)
  2160. {
  2161. child.onPointerDragEnd(pointer, viewport);
  2162. }
  2163. child.beingDragged = false;
  2164. }
  2165. }
  2166. }
  2167. }
  2168. // Object drag events and update logic
  2169. for(var i = 0; i < objects.length; i++)
  2170. {
  2171. var child = objects[i];
  2172. // Pointer drag event
  2173. if(child.beingDragged)
  2174. {
  2175. if(child.onPointerDrag !== null)
  2176. {
  2177. var lastPosition = pointer.position.clone();
  2178. lastPosition.sub(pointer.delta);
  2179. // Get position and last position in world space to calculate world pointer movement
  2180. var positionWorld = viewport.inverseMatrix.transformPoint(pointer.position);
  2181. var lastWorld = viewport.inverseMatrix.transformPoint(lastPosition);
  2182. // Pointer movement delta in world coordinates
  2183. var delta = positionWorld.clone();
  2184. delta.sub(lastWorld);
  2185. child.onPointerDrag(pointer, viewport, delta, positionWorld);
  2186. }
  2187. }
  2188. // On update
  2189. if(child.onUpdate !== null)
  2190. {
  2191. child.onUpdate();
  2192. }
  2193. }
  2194. // Update transformation matrices
  2195. object.traverse(function(child)
  2196. {
  2197. child.updateMatrix();
  2198. });
  2199. this.context.setTransform(1, 0, 0, 1, 0, 0);
  2200. // Clear canvas content
  2201. if(this.autoClear)
  2202. {
  2203. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  2204. }
  2205. // Render into the canvas
  2206. for(var i = objects.length - 1; i >= 0; i--)
  2207. {
  2208. if(objects[i].isMask)
  2209. {
  2210. continue;
  2211. }
  2212. if(objects[i].saveContextState)
  2213. {
  2214. this.context.save();
  2215. }
  2216. // Apply all masks
  2217. var masks = objects[i].masks;
  2218. for(var j = 0; j < masks.length; j++)
  2219. {
  2220. if(!masks[j].ignoreViewport)
  2221. {
  2222. viewport.matrix.setContextTransform(this.context);
  2223. }
  2224. masks[j].transform(this.context, viewport, this.canvas);
  2225. masks[j].clip(this.context, viewport, this.canvas);
  2226. }
  2227. // Set the viewport transform
  2228. if(!objects[i].ignoreViewport)
  2229. {
  2230. viewport.matrix.setContextTransform(this.context);
  2231. }
  2232. else if(masks.length > 0)
  2233. {
  2234. this.context.setTransform(1, 0, 0, 1, 0, 0);
  2235. }
  2236. // Apply the object transform to the canvas context
  2237. objects[i].transform(this.context, viewport, this.canvas);
  2238. // Style the canvas context
  2239. if(objects[i].style !== null)
  2240. {
  2241. objects[i].style(this.context, viewport, this.canvas);
  2242. }
  2243. // Draw content into the canvas.
  2244. if(objects[i].draw !== null)
  2245. {
  2246. objects[i].draw(this.context, viewport, this.canvas);
  2247. }
  2248. if(objects[i].restoreContextState)
  2249. {
  2250. this.context.restore();
  2251. }
  2252. }
  2253. };
  2254. /**
  2255. * Box is described by a minimum and maximum points.
  2256. *
  2257. * Can be used for collision detection with points and other boxes.
  2258. *
  2259. * @class
  2260. * @param {Vector2} min
  2261. * @param {Vector2} max
  2262. */
  2263. function Box2(min, max)
  2264. {
  2265. this.min = (min !== undefined) ? min : new Vector2();
  2266. this.max = (max !== undefined) ? max : new Vector2();
  2267. }
  2268. /**
  2269. * Set the box values.
  2270. *
  2271. * @param {Vector2} min
  2272. * @param {Vector2} max
  2273. */
  2274. Box2.prototype.set = function(min, max)
  2275. {
  2276. this.min.copy(min);
  2277. this.max.copy(max);
  2278. return this;
  2279. };
  2280. /**
  2281. * Set the box from a list of Vector2 points.
  2282. *
  2283. * @param {Array} points
  2284. */
  2285. Box2.prototype.setFromPoints = function(points)
  2286. {
  2287. this.min = new Vector2(+Infinity, +Infinity);
  2288. this.max = new Vector2(-Infinity, -Infinity);
  2289. for(var i = 0, il = points.length; i < il; i++)
  2290. {
  2291. this.expandByPoint(points[i]);
  2292. }
  2293. return this;
  2294. };
  2295. /**
  2296. * Set the box minimum and maximum from center point and size.
  2297. *
  2298. * @param {Vector2} center
  2299. * @param {Vector2} size
  2300. */
  2301. Box2.prototype.setFromCenterAndSize = function(center, size)
  2302. {
  2303. var v1 = new Vector2();
  2304. var halfSize = v1.copy(size).multiplyScalar(0.5);
  2305. this.min.copy(center).sub(halfSize);
  2306. this.max.copy(center).add(halfSize);
  2307. return this;
  2308. };
  2309. /**
  2310. * Clone the box into a new object.
  2311. *
  2312. * Should be used when it it necessary to make operations to this box.
  2313. *
  2314. * @return {Box2} New box object with the copy of this object.
  2315. */
  2316. Box2.prototype.clone = function()
  2317. {
  2318. var box = new Box2();
  2319. box.copy(this);
  2320. return box;
  2321. };
  2322. /**
  2323. * Copy the box value from another box.
  2324. *
  2325. * @param {Box2} point
  2326. */
  2327. Box2.prototype.copy = function(box)
  2328. {
  2329. this.min.copy(box.min);
  2330. this.max.copy(box.max);
  2331. };
  2332. /**
  2333. * Check if the box is empty (size equals zero or is negative).
  2334. *
  2335. * The box size is condireded valid on two negative axis.
  2336. *
  2337. * @return {boolean} True if the box is empty.
  2338. */
  2339. Box2.prototype.isEmpty = function()
  2340. {
  2341. return (this.max.x < this.min.x) || (this.max.y < this.min.y);
  2342. };
  2343. /**
  2344. * Calculate the center point of the box.
  2345. *
  2346. * @param {Vector2} [target] Vector to store the result.
  2347. * @return {Vector2} Central point of the box.
  2348. */
  2349. Box2.prototype.getCenter = function(target)
  2350. {
  2351. if(target === undefined)
  2352. {
  2353. target = new Vector2();
  2354. }
  2355. this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2356. return target;
  2357. };
  2358. /**
  2359. * Get the size of the box from its min and max points.
  2360. *
  2361. * @param {Vector2} [target] Vector to store the result.
  2362. * @return {Vector2} Vector with the calculated size.
  2363. */
  2364. Box2.prototype.getSize = function(target)
  2365. {
  2366. if(target === undefined)
  2367. {
  2368. target = new Vector2();
  2369. }
  2370. this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  2371. return target;
  2372. };
  2373. /**
  2374. * Expand the box to contain a new point.
  2375. *
  2376. * @param {Vector2} point
  2377. */
  2378. Box2.prototype.expandByPoint = function(point)
  2379. {
  2380. this.min.min(point);
  2381. this.max.max(point);
  2382. return this;
  2383. };
  2384. /**
  2385. * Expand the box by adding a border with the vector size.
  2386. *
  2387. * Vector is subtracted from min and added to the max points.
  2388. *
  2389. * @param {Vector2} vector
  2390. */
  2391. Box2.prototype.expandByVector = function(vector)
  2392. {
  2393. this.min.sub(vector);
  2394. this.max.add(vector);
  2395. };
  2396. /**
  2397. * Expand the box by adding a border with the scalar value.
  2398. *
  2399. * @param {number} scalar
  2400. */
  2401. Box2.prototype.expandByScalar = function(scalar)
  2402. {
  2403. this.min.addScalar(-scalar);
  2404. this.max.addScalar(scalar);
  2405. };
  2406. /**
  2407. * Check if the box contains a point inside.
  2408. *
  2409. * @param {Vector2} point
  2410. * @return {boolean} True if the box contains point.
  2411. */
  2412. Box2.prototype.containsPoint = function(point)
  2413. {
  2414. return !(point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y);
  2415. };
  2416. /**
  2417. * Check if the box fully contains another box inside (different from intersects box).
  2418. *
  2419. * Only returns true if the box is fully contained.
  2420. *
  2421. * @param {Box2} box
  2422. * @return {boolean} True if the box contains box.
  2423. */
  2424. Box2.prototype.containsBox = function(box)
  2425. {
  2426. 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;
  2427. };
  2428. /**
  2429. * Check if two boxes intersect each other, using 4 splitting planes to rule out intersections.
  2430. *
  2431. * @param {Box2} box
  2432. * @return {boolean} True if the boxes intersect each other.
  2433. */
  2434. Box2.prototype.intersectsBox = function(box)
  2435. {
  2436. 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);
  2437. };
  2438. /**
  2439. * Calculate the distance to a point.
  2440. *
  2441. * @param {Vector2} point
  2442. * @return {number} Distance to point calculated.
  2443. */
  2444. Box2.prototype.distanceToPoint = function(point)
  2445. {
  2446. var v = new Vector2();
  2447. var clampedPoint = v.copy(point).clamp(this.min, this.max);
  2448. return clampedPoint.sub(point).length();
  2449. };
  2450. /**
  2451. * Make a intersection between this box and another box.
  2452. *
  2453. * Store the result in this object.
  2454. *
  2455. * @param {Box2} box
  2456. */
  2457. Box2.prototype.intersect = function(box)
  2458. {
  2459. this.min.max(box.min);
  2460. this.max.min(box.max);
  2461. };
  2462. /**
  2463. * Make a union between this box and another box.
  2464. *
  2465. * Store the result in this object.
  2466. *
  2467. * @param {Box2} box
  2468. */
  2469. Box2.prototype.union = function(box)
  2470. {
  2471. this.min.min(box.min);
  2472. this.max.max(box.max);
  2473. };
  2474. /**
  2475. * Translate the box by a offset value, adds the offset to booth min and max.
  2476. *
  2477. * @param {Vector2} offset
  2478. */
  2479. Box2.prototype.translate = function(offset)
  2480. {
  2481. this.min.add(offset);
  2482. this.max.add(offset);
  2483. };
  2484. /**
  2485. * Checks if two boxes are equal.
  2486. *
  2487. * @param {Box2} box
  2488. * @return {boolean} True if the two boxes are equal.
  2489. */
  2490. Box2.prototype.equals = function(box)
  2491. {
  2492. return box.min.equals(this.min) && box.max.equals(this.max);
  2493. };
  2494. /**
  2495. * A mask can be used to set the drawing region.
  2496. *
  2497. * Masks are treated as objects their shape is used to filter other objects shape.
  2498. *
  2499. * Multiple mask objects can be active simultaneously, they have to be attached to the object mask list to filter the render region.
  2500. *
  2501. * A mask objects is draw using the context.clip() method.
  2502. *
  2503. * @class
  2504. * @extends {Object2D}
  2505. */
  2506. function Mask()
  2507. {
  2508. Object2D.call(this);
  2509. }
  2510. Mask.prototype = Object.create(Object2D.prototype);
  2511. Mask.prototype.isMask = true;
  2512. /**
  2513. * Clip the canvas context, to ensure that next objects being drawn are cliped to the path stored here.
  2514. *
  2515. * @param {CanvasRenderingContext2D} context Canvas 2d drawing context.
  2516. * @param {Viewport} viewport Viewport applied to the canvas.
  2517. * @param {DOM} canvas DOM canvas element where the content is being drawn.
  2518. */
  2519. Mask.prototype.clip = function(context, viewport, canvas){};
  2520. /**
  2521. * Box mask can be used to clear a box mask region.
  2522. *
  2523. * It will limit the drawing region to this box.
  2524. *
  2525. * @class
  2526. * @extends {Mask}
  2527. */
  2528. function BoxMask()
  2529. {
  2530. Mask.call(this);
  2531. /**
  2532. * Box object containing the size of the object.
  2533. */
  2534. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  2535. /**
  2536. * If inverted the mask considers the outside of the box instead of the inside.
  2537. */
  2538. this.invert = false;
  2539. }
  2540. BoxMask.prototype = Object.create(Mask.prototype);
  2541. BoxMask.prototype.isInside = function(point)
  2542. {
  2543. return this.box.containsPoint(point);
  2544. };
  2545. BoxMask.prototype.clip = function(context, viewport, canvas)
  2546. {
  2547. context.beginPath();
  2548. var width = this.box.max.x - this.box.min.x;
  2549. if(this.invert)
  2550. {
  2551. context.rect(this.box.min.x - 1e4, -5e3, 1e4, 1e4);
  2552. context.rect(this.box.max.x, -5e3, 1e4, 1e4);
  2553. context.rect(this.box.min.x, this.box.min.y - 1e4, width, 1e4);
  2554. context.rect(this.box.min.x, this.box.max.y, width, 1e4);
  2555. }
  2556. else
  2557. {
  2558. var height = this.box.max.y - this.box.min.y;
  2559. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  2560. }
  2561. context.clip();
  2562. };
  2563. /**
  2564. * Box object draw a rectangular object.
  2565. *
  2566. * Can be used as a base to implement other box objects, already implements collision for pointer events.
  2567. *
  2568. * @class
  2569. * @extends {Object2D}
  2570. */
  2571. function Box()
  2572. {
  2573. Object2D.call(this);
  2574. /**
  2575. * Box object containing the size of the object.
  2576. */
  2577. this.box = new Box2(new Vector2(-50, -50), new Vector2(50, 50));
  2578. /**
  2579. * Style of the object border line.
  2580. *
  2581. * If set null it is ignored.
  2582. */
  2583. this.strokeStyle = "#000000";
  2584. /**
  2585. * Line width, only used if a valid strokeStyle is defined.
  2586. */
  2587. this.lineWidth = 1;
  2588. /**
  2589. * Background color of the box.
  2590. *
  2591. * If set null it is ignored.
  2592. */
  2593. this.fillStyle = "#FFFFFF";
  2594. }
  2595. Box.prototype = Object.create(Object2D.prototype);
  2596. Box.prototype.onPointerEnter = function(pointer, viewport)
  2597. {
  2598. this.fillStyle = "#CCCCCC";
  2599. };
  2600. Box.prototype.onPointerLeave = function(pointer, viewport)
  2601. {
  2602. this.fillStyle = "#FFFFFF";
  2603. };
  2604. Box.prototype.isInside = function(point)
  2605. {
  2606. return this.box.containsPoint(point);
  2607. };
  2608. Box.prototype.draw = function(context, viewport, canvas)
  2609. {
  2610. var width = this.box.max.x - this.box.min.x;
  2611. var height = this.box.max.y - this.box.min.y;
  2612. if(this.fillStyle !== null)
  2613. {
  2614. context.fillStyle = this.fillStyle;
  2615. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  2616. }
  2617. if(this.strokeStyle !== null)
  2618. {
  2619. context.lineWidth = this.lineWidth;
  2620. context.strokeStyle = this.strokeStyle;
  2621. context.strokeRect(this.box.min.x, this.box.min.y, width, height);
  2622. }
  2623. };
  2624. /**
  2625. * Circle object draw a circular object, into the canvas.
  2626. *
  2627. * Can be used as a base to implement other circular objects, already implements the circle collision for pointer events.
  2628. *
  2629. * @class
  2630. * @extends {Object2D}
  2631. */
  2632. function Circle()
  2633. {
  2634. Object2D.call(this);
  2635. /**
  2636. * Radius of the circle.
  2637. */
  2638. this.radius = 10.0;
  2639. /**
  2640. * Style of the object border line.
  2641. *
  2642. * If set null it is ignored.
  2643. */
  2644. this.strokeStyle = "#000000";
  2645. /**
  2646. * Line width, only used if a valid strokeStyle is defined.
  2647. */
  2648. this.lineWidth = 1;
  2649. /**
  2650. * Background color of the circle.
  2651. *
  2652. * If set null it is ignored.
  2653. */
  2654. this.fillStyle = "#FFFFFF";
  2655. }
  2656. Circle.prototype = Object.create(Object2D.prototype);
  2657. Circle.prototype.isInside = function(point)
  2658. {
  2659. return point.length() <= this.radius;
  2660. };
  2661. Circle.prototype.onPointerEnter = function(pointer, viewport)
  2662. {
  2663. this.fillStyle = "#CCCCCC";
  2664. };
  2665. Circle.prototype.onPointerLeave = function(pointer, viewport)
  2666. {
  2667. this.fillStyle = "#FFFFFF";
  2668. };
  2669. Circle.prototype.draw = function(context, viewport, canvas)
  2670. {
  2671. context.beginPath();
  2672. context.arc(0, 0, this.radius, 0, 2 * Math.PI);
  2673. if(this.fillStyle !== null)
  2674. {
  2675. context.fillStyle = this.fillStyle;
  2676. context.fill();
  2677. }
  2678. if(this.strokeStyle !== null)
  2679. {
  2680. context.lineWidth = this.lineWidth;
  2681. context.strokeStyle = this.strokeStyle;
  2682. context.stroke();
  2683. }
  2684. };
  2685. /**
  2686. * Line object draw a line from one point to another without any kind of interpolation.
  2687. *
  2688. * For drawing lines with interpolation check {BezierCurve}
  2689. *
  2690. * @class
  2691. * @extends {Object2D}
  2692. */
  2693. function Line()
  2694. {
  2695. Object2D.call(this);
  2696. /**
  2697. * Initial point of the line.
  2698. *
  2699. * Can be equal to the position object of another object. Making it automatically follow that object.
  2700. */
  2701. this.from = new Vector2();
  2702. /**
  2703. * Final point of the line.
  2704. *
  2705. * Can be equal to the position object of another object. Making it automatically follow that object.
  2706. */
  2707. this.to = new Vector2();
  2708. /**
  2709. * Dash line pattern to be used, if empty draws a solid line.
  2710. *
  2711. * Dash pattern is defined as the size of dashes as pairs of space with no line and with line.
  2712. *
  2713. * E.g if the dash pattern is [1, 2] we get 1 point with line, 2 without line repeat infinitelly.
  2714. */
  2715. this.dashPattern = [5, 5];
  2716. /**
  2717. * Style of the object line.
  2718. */
  2719. this.strokeStyle = "#000000";
  2720. /**
  2721. * Line width of the line.
  2722. */
  2723. this.lineWidth = 1;
  2724. }
  2725. Line.prototype = Object.create(Object2D.prototype);
  2726. Line.prototype.style = function(context, viewport, canvas)
  2727. {
  2728. context.lineWidth = this.lineWidth;
  2729. context.strokeStyle = this.strokeStyle;
  2730. context.setLineDash(this.dashPattern);
  2731. };
  2732. Line.prototype.draw = function(context, viewport, canvas)
  2733. {
  2734. context.beginPath();
  2735. context.moveTo(this.from.x, this.from.y);
  2736. context.lineTo(this.to.x, this.to.y);
  2737. context.stroke();
  2738. };
  2739. /**
  2740. * Image object is used to draw an image from URL.
  2741. *
  2742. * @class
  2743. * @param {string} src Source URL of the image.
  2744. * @extends {Object2D}
  2745. */
  2746. function Image(src)
  2747. {
  2748. Object2D.call(this);
  2749. /**
  2750. * Box object containing the size of the object.
  2751. */
  2752. this.box = new Box2();
  2753. /**
  2754. * Image source DOM element.
  2755. */
  2756. this.image = document.createElement("img");
  2757. if(src !== undefined)
  2758. {
  2759. this.setImage(src);
  2760. }
  2761. }
  2762. Image.prototype = Object.create(Object2D.prototype);
  2763. /**
  2764. * Set the image of the object.
  2765. *
  2766. * Automatically sets the box size to match the image.
  2767. *
  2768. * @param {string} src Source URL of the image.
  2769. */
  2770. Image.prototype.setImage = function(src)
  2771. {
  2772. var self = this;
  2773. this.image.onload = function()
  2774. {
  2775. self.box.min.set(0, 0);
  2776. self.box.max.set(this.naturalWidth, this.naturalHeight);
  2777. };
  2778. this.image.src = src;
  2779. };
  2780. Image.prototype.isInside = function(point)
  2781. {
  2782. return this.box.containsPoint(point);
  2783. };
  2784. Image.prototype.draw = function(context, viewport, canvas)
  2785. {
  2786. if(this.image.src.length > 0)
  2787. {
  2788. 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);
  2789. }
  2790. };
  2791. /**
  2792. * A DOM object transformed using CSS3D to be included in the scene.
  2793. *
  2794. * DOM objects always stay on top of everything else, it is not possible to layer these object with regular canvas objects.
  2795. *
  2796. * By default mouse events are not supported for these objects (it does not implement pointer collision checking). Use the DOM events for interaction with these types of objects.
  2797. *
  2798. * @class
  2799. * @param {Element} parentDOM Parent DOM element that contains the drawing canvas.
  2800. * @param {string} type Type of the DOM element (e.g. "div", "p", ...)
  2801. * @extends {Object2D}
  2802. */
  2803. function DOM(parentDOM, type)
  2804. {
  2805. Object2D.call(this);
  2806. /**
  2807. * Parent element that contains this DOM div.
  2808. *
  2809. * @type {Element}
  2810. */
  2811. this.parentDOM = parentDOM;
  2812. /**
  2813. * DOM element contained by this object.
  2814. *
  2815. * By default it has the pointerEvents style set to none. In order to use any DOM event with this object first you have to set the element.style.pointerEvents to "auto".
  2816. *
  2817. * @type {Element}
  2818. */
  2819. this.element = document.createElement(type || "div");
  2820. this.element.style.transformStyle = "preserve-3d";
  2821. this.element.style.position = "absolute";
  2822. this.element.style.top = "0px";
  2823. this.element.style.bottom = "0px";
  2824. this.element.style.transformOrigin = "0px 0px";
  2825. this.element.style.overflow = "auto";
  2826. this.element.style.pointerEvents = "none";
  2827. /**
  2828. * Size of the DOM element (in world coordinates).
  2829. */
  2830. this.size = new Vector2(100, 100);
  2831. }
  2832. DOM.prototype = Object.create(Object2D.prototype);
  2833. /**
  2834. * DOM object implements onAdd() method to automatically attach the DOM object to the DOM tree.
  2835. */
  2836. DOM.prototype.onAdd = function()
  2837. {
  2838. this.parentDOM.appendChild(this.element);
  2839. };
  2840. /**
  2841. * DOM object implements onAdd() method to automatically remove the DOM object to the DOM tree.
  2842. */
  2843. DOM.prototype.onRemove = function()
  2844. {
  2845. this.parentDOM.removeChild(this.element);
  2846. };
  2847. DOM.prototype.transform = function(context, viewport, canvas)
  2848. {
  2849. // CSS transformation matrix
  2850. if(this.ignoreViewport)
  2851. {
  2852. this.element.style.transform = this.globalMatrix.cssTransform();
  2853. }
  2854. else
  2855. {
  2856. var projection = viewport.matrix.clone();
  2857. projection.multiply(this.globalMatrix);
  2858. this.element.style.transform = projection.cssTransform();
  2859. }
  2860. // Size of the element
  2861. this.element.style.width = this.size.x + "px";
  2862. this.element.style.height = this.size.y + "px";
  2863. // Visibility
  2864. this.element.style.display = this.visible ? "block" : "none";
  2865. };
  2866. /**
  2867. * Pattern object draw a image repeated as a pattern.
  2868. *
  2869. * Its similar to the Image class but the image can be repeat infinitely.
  2870. *
  2871. * @class
  2872. * @extends {Object2D}
  2873. * @param {string} src Source image URL.
  2874. */
  2875. function Pattern(src)
  2876. {
  2877. Object2D.call(this);
  2878. /**
  2879. * Box object containing the size of the object.
  2880. */
  2881. this.box = new Box2();
  2882. /**
  2883. * Image source DOM element.
  2884. */
  2885. this.image = document.createElement("img");
  2886. /**
  2887. * A DOMString indicating how to repeat the pattern image.
  2888. */
  2889. this.repetition = "repeat";
  2890. if(src !== undefined)
  2891. {
  2892. this.setImage(src);
  2893. }
  2894. }
  2895. Pattern.prototype = Object.create(Object2D.prototype);
  2896. /**
  2897. * Set the image of the object.
  2898. *
  2899. * Automatically sets the box size to match the image.
  2900. */
  2901. Pattern.prototype.setImage = function(src)
  2902. {
  2903. var self = this;
  2904. this.image.onload = function()
  2905. {
  2906. self.box.min.set(0, 0);
  2907. self.box.max.set(this.naturalWidth, this.naturalHeight);
  2908. };
  2909. this.image.src = src;
  2910. };
  2911. Pattern.prototype.isInside = function(point)
  2912. {
  2913. return this.box.containsPoint(point);
  2914. };
  2915. Pattern.prototype.draw = function(context, viewport, canvas)
  2916. {
  2917. var width = this.box.max.x - this.box.min.x;
  2918. var height = this.box.max.y - this.box.min.y;
  2919. if(this.image.src.length > 0)
  2920. {
  2921. var pattern = context.createPattern(this.image, this.repetition);
  2922. context.fillStyle = pattern;
  2923. context.fillRect(this.box.min.x, this.box.min.y, width, height);
  2924. }
  2925. };
  2926. /**
  2927. * Graph object is used to draw simple graph data into the canvas.
  2928. *
  2929. * Graph data is composed of X, Y values.
  2930. *
  2931. * @class
  2932. * @extends {Object2D}
  2933. */
  2934. function Graph()
  2935. {
  2936. Object2D.call(this);
  2937. /**
  2938. * Graph object containing the size of the object.
  2939. */
  2940. this.box = new Box2(new Vector2(-50, -35), new Vector2(50, 35));
  2941. /**
  2942. * Color of the box border line.
  2943. */
  2944. this.strokeStyle = "rgb(0, 153, 255)";
  2945. /**
  2946. * Line width.
  2947. */
  2948. this.lineWidth = 1;
  2949. /**
  2950. * Background color of the box.
  2951. */
  2952. this.fillStyle = "rgba(0, 153, 255, 0.3)";
  2953. /**
  2954. * Minimum value of the graph.
  2955. */
  2956. this.min = 0;
  2957. /**
  2958. * Maximum value of the graph.
  2959. */
  2960. this.max = 10;
  2961. /**
  2962. * Data to be presented in the graph.
  2963. *
  2964. * The array should store numeric values.
  2965. */
  2966. this.data = [];
  2967. }
  2968. Graph.prototype = Object.create(Object2D.prototype);
  2969. Graph.prototype.isInside = function(point)
  2970. {
  2971. return this.box.containsPoint(point);
  2972. };
  2973. Graph.prototype.draw = function(context, viewport, canvas)
  2974. {
  2975. if(this.data.length === 0)
  2976. {
  2977. return;
  2978. }
  2979. var width = this.box.max.x - this.box.min.x;
  2980. var height = this.box.max.y - this.box.min.y;
  2981. context.lineWidth = this.lineWidth;
  2982. context.strokeStyle = this.strokeStyle;
  2983. context.beginPath();
  2984. var step = width / (this.data.length - 1);
  2985. var gamma = this.max - this.min;
  2986. context.moveTo(this.box.min.x, this.box.max.y - ((this.data[0] - this.min) / gamma) * height);
  2987. for(var i = 1, s = step; i < this.data.length; s += step, i++)
  2988. {
  2989. context.lineTo(this.box.min.x + s, this.box.max.y - ((this.data[i] - this.min) / gamma) * height);
  2990. }
  2991. context.stroke();
  2992. if(this.fillStyle !== null)
  2993. {
  2994. context.fillStyle = this.fillStyle;
  2995. context.lineTo(this.box.max.x, this.box.max.y);
  2996. context.lineTo(this.box.min.x, this.box.max.y);
  2997. context.fill();
  2998. }
  2999. };
  3000. /**
  3001. * Bezier curve object draw as bezier curve between two points.
  3002. *
  3003. * @class
  3004. * @extends {Line}
  3005. */
  3006. function BezierCurve()
  3007. {
  3008. Line.call(this);
  3009. /**
  3010. * Initial position control point, indicates the tangent of the bezier curve on the first point.
  3011. *
  3012. * @type {Vector2}
  3013. */
  3014. this.fromCp = new Vector2();
  3015. /**
  3016. * Final position control point, indicates the tangent of the bezier curve on the last point.
  3017. *
  3018. * @type {Vector2}
  3019. */
  3020. this.toCp = new Vector2();
  3021. }
  3022. BezierCurve.prototype = Object.create(Line.prototype);
  3023. /**
  3024. * Create a bezier curve helper, to edit the bezier curve anchor points.
  3025. *
  3026. * Helper objects are added to the parent of the curve object.
  3027. *
  3028. * @static
  3029. * @param {BezierCurve} object Object to create the helper for.
  3030. */
  3031. BezierCurve.curveHelper = function(object)
  3032. {
  3033. var fromCp = new Circle();
  3034. fromCp.radius = 3;
  3035. fromCp.layer = object.layer + 1;
  3036. fromCp.draggable = true;
  3037. fromCp.onPointerDrag = function(pointer, viewport, delta)
  3038. {
  3039. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3040. object.fromCp.copy(fromCp.position);
  3041. };
  3042. object.parent.add(fromCp);
  3043. var fromLine = new Line();
  3044. fromLine.from = object.from;
  3045. fromLine.to = object.fromCp;
  3046. object.parent.add(fromLine);
  3047. var toCp = new Circle();
  3048. toCp.radius = 3;
  3049. toCp.layer = object.layer + 1;
  3050. toCp.draggable = true;
  3051. toCp.onPointerDrag = function(pointer, viewport, delta)
  3052. {
  3053. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3054. object.toCp.copy(toCp.position);
  3055. };
  3056. object.parent.add(toCp);
  3057. var toLine = new Line();
  3058. toLine.from = object.to;
  3059. toLine.to = object.toCp;
  3060. object.parent.add(toLine);
  3061. };
  3062. BezierCurve.prototype.draw = function(context, viewport, canvas)
  3063. {
  3064. context.beginPath();
  3065. context.moveTo(this.from.x, this.from.y);
  3066. context.bezierCurveTo(this.fromCp.x, this.fromCp.y, this.toCp.x, this.toCp.y, this.to.x, this.to.y);
  3067. context.stroke();
  3068. };
  3069. /**
  3070. * Bezier curve object draw as bezier curve between two points.
  3071. *
  3072. * @class
  3073. * @extends {Object2D}
  3074. */
  3075. function QuadraticCurve()
  3076. {
  3077. Line.call(this);
  3078. /**
  3079. * Control point of the quadratic curve used to control the curvature of the line between the from and to point.
  3080. *
  3081. * The curve is interpolated in the direction of the control point it defined the path of the curve.
  3082. *
  3083. * @type {Vector2}
  3084. */
  3085. this.controlPoint = new Vector2();
  3086. }
  3087. QuadraticCurve.prototype = Object.create(Line.prototype);
  3088. /**
  3089. * Create a quadratic curve helper, to edit the curve control point.
  3090. *
  3091. * Helper objects are added to the parent of the curve object.
  3092. *
  3093. * @static
  3094. * @param {QuadraticCurve} object Object to create the helper for.
  3095. */
  3096. QuadraticCurve.curveHelper = function(object)
  3097. {
  3098. var fromLine = new Line();
  3099. fromLine.from = object.from;
  3100. fromLine.to = object.controlPoint;
  3101. object.parent.add(fromLine);
  3102. var controlPoint = new Circle();
  3103. controlPoint.radius = 3;
  3104. controlPoint.layer = object.layer + 1;
  3105. controlPoint.draggable = true;
  3106. controlPoint.position = object.controlPoint;
  3107. controlPoint.onPointerDrag = function(pointer, viewport, delta)
  3108. {
  3109. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3110. object.controlPoint.copy(controlPoint.position);
  3111. };
  3112. object.parent.add(controlPoint);
  3113. var toLine = new Line();
  3114. toLine.from = object.to;
  3115. toLine.to = object.controlPoint;
  3116. object.parent.add(toLine);
  3117. };
  3118. QuadraticCurve.prototype.draw = function(context, viewport, canvas)
  3119. {
  3120. context.beginPath();
  3121. context.moveTo(this.from.x, this.from.y);
  3122. context.quadraticCurveTo(this.controlPoint.x, this.controlPoint.y, this.to.x, this.to.y);
  3123. context.stroke();
  3124. };
  3125. /**
  3126. * Rounded box object draw a rectangular object with rounded corners.
  3127. *
  3128. * @class
  3129. * @extends {Box}
  3130. */
  3131. function RoundedBox()
  3132. {
  3133. Box.call(this);
  3134. /**
  3135. * Radius of the circular section that makes up the box corners.
  3136. *
  3137. * @type {number}
  3138. */
  3139. this.radius = 5;
  3140. }
  3141. RoundedBox.prototype = Object.create(Box.prototype);
  3142. /**
  3143. * Draw a rounded rectangle into the canvas context using path to draw the rounded rectangle.
  3144. *
  3145. * @param {CanvasRenderingContext2D} context
  3146. * @param {number} x The top left x coordinate
  3147. * @param {number} y The top left y coordinate
  3148. * @param {number} width The width of the rectangle
  3149. * @param {number} height The height of the rectangle
  3150. * @param {number} radius Radius of the rectangle corners.
  3151. */
  3152. RoundedBox.roundRect = function(context, x, y, width, height, radius)
  3153. {
  3154. context.beginPath();
  3155. context.moveTo(x + radius, y);
  3156. context.lineTo(x + width - radius, y);
  3157. context.quadraticCurveTo(x + width, y, x + width, y + radius);
  3158. context.lineTo(x + width, y + height - radius);
  3159. context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  3160. context.lineTo(x + radius, y + height);
  3161. context.quadraticCurveTo(x, y + height, x, y + height - radius);
  3162. context.lineTo(x, y + radius);
  3163. context.quadraticCurveTo(x, y, x + radius, y);
  3164. context.closePath();
  3165. };
  3166. RoundedBox.prototype.draw = function(context, viewport, canvas)
  3167. {
  3168. var width = this.box.max.x - this.box.min.x;
  3169. var height = this.box.max.y - this.box.min.y;
  3170. if(this.fillStyle !== null)
  3171. {
  3172. context.fillStyle = this.fillStyle;
  3173. RoundedBox.roundRect(context, this.box.min.x, this.box.min.y, width, height, this.radius);
  3174. context.fill();
  3175. }
  3176. if(this.strokeStyle !== null)
  3177. {
  3178. context.lineWidth = this.lineWidth;
  3179. context.strokeStyle = this.strokeStyle;
  3180. RoundedBox.roundRect(context, this.box.min.x, this.box.min.y, width, height, this.radius);
  3181. context.stroke();
  3182. }
  3183. };
  3184. /**
  3185. * Node connector is used to connect a output of a node to a input of another node.
  3186. *
  3187. * Some nodes inputs/outputs might support just one or multiple connections.
  3188. *
  3189. * @class NodeConnector
  3190. */
  3191. function NodeConnector()
  3192. {
  3193. BezierCurve.call(this);
  3194. this.lineWidth = 2;
  3195. /**
  3196. * Origin hook that is attached to a node.
  3197. *
  3198. * @type {NodeSocket}
  3199. */
  3200. this.outputSocket = null;
  3201. /**
  3202. * Destination hook that is attached to a node.
  3203. *
  3204. * @type {NodeSocket}
  3205. */
  3206. this.inputSocket = null;
  3207. }
  3208. NodeConnector.prototype = Object.create(BezierCurve.prototype);
  3209. NodeConnector.prototype.destroy = function()
  3210. {
  3211. BezierCurve.prototype.destroy.call(this);
  3212. if(this.outputSocket !== null)
  3213. {
  3214. this.outputSocket.connector = null;
  3215. }
  3216. if(this.inputSocket !== null)
  3217. {
  3218. this.inputSocket.connector = null;
  3219. }
  3220. };
  3221. NodeConnector.prototype.onUpdate = function()
  3222. {
  3223. if(this.outputSocket !== null)
  3224. {
  3225. this.from.copy(this.outputSocket.position);
  3226. }
  3227. if(this.inputSocket !== null)
  3228. {
  3229. this.to.copy(this.inputSocket.position);
  3230. }
  3231. // Center control points
  3232. this.fromCp.copy(this.from);
  3233. this.fromCp.add(this.to);
  3234. this.fromCp.multiplyScalar(0.5);
  3235. this.toCp.copy(this.fromCp);
  3236. var curvature = 0.5;
  3237. // Check vertical/horizontal distances
  3238. var yDistance = this.to.y - this.from.y;
  3239. var xDistance = this.to.x - this.from.x;
  3240. // Apply a offset to the control points
  3241. if(Math.abs(xDistance) > Math.abs(yDistance))
  3242. {
  3243. this.toCp.x += xDistance * curvature;
  3244. this.fromCp.x -= xDistance * curvature;
  3245. }
  3246. else
  3247. {
  3248. this.toCp.y += yDistance * curvature;
  3249. this.fromCp.y -= yDistance * curvature;
  3250. }
  3251. };
  3252. /**
  3253. * Represents a node hook point. Is attached to the node element and represented visually.
  3254. *
  3255. * Can be used as a node input, output or as a bidirectional connection.
  3256. *
  3257. * @class NodeSocket
  3258. * @param {Node} node Node of this hook.
  3259. * @param {number} direction Direction of the hook.
  3260. * @param {string} type Data type of the node socket.
  3261. * @param {string} name Name of the node socket.
  3262. */
  3263. function NodeSocket(node, direction, type, name)
  3264. {
  3265. Circle.call(this);
  3266. this.draggable = true;
  3267. this.radius = 6;
  3268. this.layer = 1;
  3269. /**
  3270. * Name of the socket presented to the user.
  3271. *
  3272. * @type {string}
  3273. */
  3274. this.name = name !== undefined ? name : "";
  3275. /**
  3276. * Type of data available from this socket, only hooks of the same type can be connected.
  3277. *
  3278. * Should directly store data type as text
  3279. *
  3280. * @type {string}
  3281. */
  3282. this.type = type !== undefined ? type : "";
  3283. /**
  3284. * Direction of the node hook.
  3285. *
  3286. * @type {number}
  3287. */
  3288. this.direction = direction;
  3289. /**
  3290. * Node where this input element in attached.
  3291. *
  3292. * @type {Node}
  3293. */
  3294. this.node = node;
  3295. /**
  3296. * Node connector used to connect this hook to another node hook.
  3297. *
  3298. * @type {NodeConnector}
  3299. */
  3300. this.connector = null;
  3301. /**
  3302. * Text object used to present the name of the socket.
  3303. *
  3304. * @type {Text}
  3305. */
  3306. this.text = new Text();
  3307. this.text.text = this.name;
  3308. if(this.direction === NodeSocket.INPUT)
  3309. {
  3310. this.text.position.x -= 10;
  3311. this.text.textAlign = "right";
  3312. }
  3313. else if(this.direction === NodeSocket.OUTPUT)
  3314. {
  3315. this.text.position.x += 10;
  3316. this.text.textAlign = "left";
  3317. }
  3318. this.add(this.text);
  3319. }
  3320. /**
  3321. * Input hook can only be connected to an output.
  3322. *
  3323. * Is used to read data from the output.
  3324. *
  3325. * @type {number}
  3326. */
  3327. NodeSocket.INPUT = 1;
  3328. /**
  3329. * Output hook can only be connected to an input.
  3330. *
  3331. * Writes data to the output.
  3332. *
  3333. * @type {number}
  3334. */
  3335. NodeSocket.OUTPUT = 2;
  3336. NodeSocket.prototype = Object.create(Circle.prototype);
  3337. /**
  3338. * Connect this node socket to another socket.
  3339. *
  3340. * Sockets have to be compatible otherwise the connection cannot be made and an error will be thrown.
  3341. *
  3342. * @param {NodeSocket} socket Socket to be connected with this
  3343. * @return {NodeConnector} Node connector created.
  3344. */
  3345. NodeSocket.prototype.connectTo = function(socket)
  3346. {
  3347. if(!this.isCompatible(socket))
  3348. {
  3349. throw new Error("Sockets are not compatible they cannot be connected.");
  3350. }
  3351. var connector = new NodeConnector();
  3352. this.attachConnector(connector);
  3353. socket.attachConnector(connector);
  3354. return connector;
  3355. };
  3356. /**
  3357. * Attach a node connector to this socket. Sets the correct input/output attributes on the socket and the connector.
  3358. *
  3359. * Automatically adds the connector to the same parent and the node socket if no parent defined for the connector.
  3360. *
  3361. * @param {NodeConnector} connector Connector to be attached to this socket.
  3362. */
  3363. NodeSocket.prototype.attachConnector = function(connector)
  3364. {
  3365. if(this.direction === NodeSocket.INPUT)
  3366. {
  3367. connector.inputSocket = this;
  3368. }
  3369. else if(this.direction === NodeSocket.OUTPUT)
  3370. {
  3371. connector.outputSocket = this;
  3372. }
  3373. this.connector = connector;
  3374. if(connector.parent === null)
  3375. {
  3376. this.parent.add(connector);
  3377. }
  3378. };
  3379. /**
  3380. * Check if this socket can be connected (is compatible) with another socket.
  3381. *
  3382. * For two sockets to be compatible the data flow should be correct (one input and a output) and they should carry the same data type.
  3383. *
  3384. * @param {NodeSocket} socket Socket to verify compatibility with.
  3385. * @return {boolean} Returns true if the two sockets are compatible.
  3386. */
  3387. NodeSocket.prototype.isCompatible = function(socket)
  3388. {
  3389. return this.direction !== socket.direction && this.type === socket.type;
  3390. };
  3391. NodeSocket.prototype.destroy = function()
  3392. {
  3393. Circle.prototype.destroy.call(this);
  3394. if(this.connector !== null)
  3395. {
  3396. this.connector.destroy();
  3397. }
  3398. };
  3399. NodeSocket.prototype.onPointerDragStart = function(pointer, viewport)
  3400. {
  3401. if(this.connector === null)
  3402. {
  3403. this.attachConnector(new NodeConnector());
  3404. }
  3405. };
  3406. NodeSocket.prototype.onPointerDrag = function(pointer, viewport, delta, position)
  3407. {
  3408. if(this.connector !== null)
  3409. {
  3410. if(this.direction === NodeSocket.INPUT)
  3411. {
  3412. this.connector.from.copy(position);
  3413. }
  3414. else if(this.direction === NodeSocket.OUTPUT)
  3415. {
  3416. this.connector.to.copy(position);
  3417. }
  3418. }
  3419. };
  3420. NodeSocket.prototype.onPointerDragEnd = function(pointer, viewport)
  3421. {
  3422. if(this.connector !== null)
  3423. {
  3424. var position = viewport.inverseMatrix.transformPoint(pointer.position);
  3425. var objects = this.parent.getWorldPointIntersections(position);
  3426. var found = false;
  3427. for(var i = 0; i < objects.length; i++)
  3428. {
  3429. if(objects[i] instanceof NodeSocket)
  3430. {
  3431. if(this.isCompatible(objects[i]))
  3432. {
  3433. objects[i].attachConnector(this.connector);
  3434. found = true;
  3435. break;
  3436. }
  3437. }
  3438. }
  3439. if(!found)
  3440. {
  3441. this.connector.destroy();
  3442. }
  3443. }
  3444. };
  3445. /**
  3446. * Node objects can be connected between them to create graphs.
  3447. *
  3448. * 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.
  3449. *
  3450. * This class implements node basic functionality, the logic to connected node and define inputs/outputs of the nodes.
  3451. *
  3452. * @class Node
  3453. */
  3454. function Node()
  3455. {
  3456. RoundedBox.call(this);
  3457. this.draggable = true;
  3458. /**
  3459. * List of inputs of the node.
  3460. *
  3461. * @type {NodeSocket[]}
  3462. */
  3463. this.inputs = [];
  3464. /**
  3465. * List of outputs of the node.
  3466. *
  3467. * @type {NodeSocket[]}
  3468. */
  3469. this.outputs = [];
  3470. }
  3471. Node.prototype = Object.create(RoundedBox.prototype);
  3472. /**
  3473. * This method should be used for the node to register their socket inputs/outputs.
  3474. *
  3475. * It is called automatically after the node is added to the node graph to create sockets.
  3476. */
  3477. Node.prototype.registerSockets = null;
  3478. /**
  3479. * Add input to this node, can be connected to other nodes to receive data.
  3480. *
  3481. * @param {string} type Data type of the node socket.
  3482. * @param {string} name Name of the node socket.
  3483. * @return {NodeSocket} Node socket created for this node.
  3484. */
  3485. Node.prototype.addInput = function(type, name)
  3486. {
  3487. var socket = new NodeSocket(this, NodeSocket.INPUT, type, name);
  3488. this.inputs.push(socket);
  3489. this.parent.add(socket);
  3490. return socket;
  3491. };
  3492. /**
  3493. * Add output socket to this node, can be connected to other nodes to send data.
  3494. *
  3495. * @param {string} type Data type of the node socket.
  3496. * @param {string} name Name of the node socket.
  3497. * @return {NodeSocket} Node socket created for this node.
  3498. */
  3499. Node.prototype.addOutput = function(type, name)
  3500. {
  3501. var socket = new NodeSocket(this, NodeSocket.OUTPUT, type, name);
  3502. this.outputs.push(socket);
  3503. this.parent.add(socket);
  3504. return socket;
  3505. };
  3506. Node.prototype.destroy = function()
  3507. {
  3508. RoundedBox.prototype.destroy.call(this);
  3509. for(var i = 0; i < this.inputs.length; i++)
  3510. {
  3511. this.inputs[i].destroy();
  3512. }
  3513. for(var i = 0; i < this.outputs.length; i++)
  3514. {
  3515. this.outputs[i].destroy();
  3516. }
  3517. };
  3518. Node.prototype.onUpdate = function()
  3519. {
  3520. var height = this.box.max.y - this.box.min.y;
  3521. // Input hooks position
  3522. var step = height / (this.inputs.length + 1);
  3523. var start = this.box.min.y + step;
  3524. for(var i = 0; i < this.inputs.length; i++)
  3525. {
  3526. this.inputs[i].position.set(this.position.x + this.box.min.x, this.position.y + (start + step * i));
  3527. }
  3528. // Output hooks position
  3529. step = height / (this.outputs.length + 1);
  3530. start = this.box.min.y + step;
  3531. for(var i = 0; i < this.outputs.length; i++)
  3532. {
  3533. this.outputs[i].position.set(this.position.x + this.box.max.x, this.position.y + (start + step * i));
  3534. }
  3535. };
  3536. /**
  3537. * Node graph object should be used as a container for node elements.
  3538. *
  3539. * The node graph object specifies how the nodes are processed, each individual node can store and process data, the node graph specified how this information is processed.
  3540. *
  3541. * All node elements are stored as children of the node graph.
  3542. *
  3543. * @class NodeGraph
  3544. */
  3545. function NodeGraph()
  3546. {
  3547. Object2D.call(this);
  3548. }
  3549. NodeGraph.prototype = Object.create(Object2D.prototype);
  3550. /**
  3551. * Create and add a new node of specific node type to the graph.
  3552. *
  3553. * Automatically finds an empty space as close as possible to other nodes to add this new node.
  3554. *
  3555. * @param {Node} node Node object to be added.
  3556. * @return {Node} Node created (already added to the graph).
  3557. */
  3558. NodeGraph.prototype.addNode = function(node)
  3559. {
  3560. // Check available position on screen.
  3561. var x = 0, y = 0;
  3562. for(var i = 0; i < this.children.length; i++)
  3563. {
  3564. if(this.children[i].position.x > x)
  3565. {
  3566. x = this.children[i].position.x;
  3567. }
  3568. if(this.children[i].position.y > y)
  3569. {
  3570. y = this.children[i].position.y;
  3571. }
  3572. }
  3573. // Create and add new node
  3574. node.position.set(x + 300, y / 2.0);
  3575. this.add(node);
  3576. if(node.registerSockets !== null)
  3577. {
  3578. node.registerSockets();
  3579. }
  3580. return node;
  3581. };
  3582. /**
  3583. * Class contains helper functions to create editing object tools.
  3584. *
  3585. * @class
  3586. */
  3587. function Helpers(){}
  3588. /**
  3589. * Create a rotation tool helper.
  3590. *
  3591. * When the object is dragged is changes the parent object rotation.
  3592. *
  3593. * @static
  3594. */
  3595. Helpers.rotateTool = function(object)
  3596. {
  3597. var tool = new Circle();
  3598. tool.radius = 4;
  3599. tool.layer = object.layer + 1;
  3600. tool.onPointerDrag = function(pointer, viewport, delta)
  3601. {
  3602. object.rotation += delta.x * 1e-3;
  3603. };
  3604. object.add(tool);
  3605. };
  3606. /**
  3607. * Create a box resize helper and attach it to an object to change the size of the object box.
  3608. *
  3609. * 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.
  3610. *
  3611. * This method required to object to have a box property.
  3612. *
  3613. * @static
  3614. */
  3615. Helpers.boxResizeTool = function(object)
  3616. {
  3617. if(object.box === undefined)
  3618. {
  3619. console.warn("escher.js: Helpers.boxResizeTool(), object box property missing.");
  3620. return;
  3621. }
  3622. function updateHelpers()
  3623. {
  3624. topRight.position.copy(object.box.min);
  3625. bottomLeft.position.copy(object.box.max);
  3626. topLeft.position.set(object.box.max.x, object.box.min.y);
  3627. bottomRight.position.set(object.box.min.x, object.box.max.y);
  3628. }
  3629. var topRight = new Circle();
  3630. topRight.radius = 4;
  3631. topRight.layer = object.layer + 1;
  3632. topRight.draggable = true;
  3633. topRight.onPointerDrag = function(pointer, viewport, delta)
  3634. {
  3635. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3636. object.box.min.copy(topRight.position);
  3637. updateHelpers();
  3638. };
  3639. object.add(topRight);
  3640. var topLeft = new Circle();
  3641. topLeft.radius = 4;
  3642. topLeft.layer = object.layer + 1;
  3643. topLeft.draggable = true;
  3644. topLeft.onPointerDrag = function(pointer, viewport, delta)
  3645. {
  3646. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3647. object.box.max.x = topLeft.position.x;
  3648. object.box.min.y = topLeft.position.y;
  3649. updateHelpers();
  3650. };
  3651. object.add(topLeft);
  3652. var bottomLeft = new Circle();
  3653. bottomLeft.radius = 4;
  3654. bottomLeft.layer = object.layer + 1;
  3655. bottomLeft.draggable = true;
  3656. bottomLeft.onPointerDrag = function(pointer, viewport, delta)
  3657. {
  3658. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3659. object.box.max.copy(bottomLeft.position);
  3660. updateHelpers();
  3661. };
  3662. object.add(bottomLeft);
  3663. var bottomRight = new Circle();
  3664. bottomRight.radius = 4;
  3665. bottomRight.layer = object.layer + 1;
  3666. bottomRight.draggable = true;
  3667. bottomRight.onPointerDrag = function(pointer, viewport, delta)
  3668. {
  3669. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  3670. object.box.min.x = bottomRight.position.x;
  3671. object.box.max.y = bottomRight.position.y;
  3672. updateHelpers();
  3673. };
  3674. object.add(bottomRight);
  3675. updateHelpers();
  3676. };
  3677. exports.BezierCurve = BezierCurve;
  3678. exports.Box = Box;
  3679. exports.Box2 = Box2;
  3680. exports.BoxMask = BoxMask;
  3681. exports.Circle = Circle;
  3682. exports.DOM = DOM;
  3683. exports.EventManager = EventManager;
  3684. exports.Graph = Graph;
  3685. exports.Helpers = Helpers;
  3686. exports.Image = Image;
  3687. exports.Key = Key;
  3688. exports.Line = Line;
  3689. exports.Mask = Mask;
  3690. exports.Matrix = Matrix;
  3691. exports.MultiLineText = MultiLineText;
  3692. exports.Node = Node;
  3693. exports.NodeConnector = NodeConnector;
  3694. exports.NodeGraph = NodeGraph;
  3695. exports.NodeSocket = NodeSocket;
  3696. exports.Object2D = Object2D;
  3697. exports.Pattern = Pattern;
  3698. exports.Pointer = Pointer;
  3699. exports.QuadraticCurve = QuadraticCurve;
  3700. exports.Renderer = Renderer;
  3701. exports.RoundedBox = RoundedBox;
  3702. exports.Text = Text;
  3703. exports.UUID = UUID;
  3704. exports.Vector2 = Vector2;
  3705. exports.Viewport = Viewport;
  3706. exports.ViewportControls = ViewportControls;
  3707. Object.defineProperty(exports, '__esModule', { value: true });
  3708. })));