babylon.prim2dBase.ts 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125
  1. module BABYLON {
  2. export class PrepareRender2DContext {
  3. constructor() {
  4. this.forceRefreshPrimitive = false;
  5. }
  6. /**
  7. * True if the primitive must be refreshed no matter what
  8. * This mode is needed because sometimes the primitive doesn't change by itself, but external changes make a refresh of its InstanceData necessary
  9. */
  10. forceRefreshPrimitive: boolean;
  11. }
  12. export class Render2DContext {
  13. constructor(renderMode: number) {
  14. this._renderMode = renderMode;
  15. this.useInstancing = false;
  16. this.groupInfoPartData = null;
  17. this.partDataStartIndex = this.partDataEndIndex = null;
  18. this.instancedBuffers = null;
  19. }
  20. /**
  21. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  22. */
  23. get renderMode(): number {
  24. return this._renderMode;
  25. }
  26. /**
  27. * If true hardware instancing is supported and must be used for the rendering. The groupInfoPartData._partBuffer must be used.
  28. * If false rendering on a per primitive basis must be made. The following properties must be used
  29. * - groupInfoPartData._partData: contains the primitive instances data to render
  30. * - partDataStartIndex: the index into instanceArrayData of the first instance to render.
  31. * - partDataCount: the number of primitive to render
  32. */
  33. useInstancing: boolean;
  34. /**
  35. * If specified, must take precedence from the groupInfoPartData. partIndex is the same as groupInfoPardData
  36. */
  37. instancedBuffers: WebGLBuffer[];
  38. /**
  39. * To use when instancedBuffers is specified, gives the count of instances to draw
  40. */
  41. instancesCount: number;
  42. /**
  43. * Contains the data related to the primitives instances to render
  44. */
  45. groupInfoPartData: GroupInfoPartData[];
  46. /**
  47. * The index into groupInfoPartData._partData of the first primitive to render. This is an index, not an offset: it represent the nth primitive which is the first to render.
  48. */
  49. partDataStartIndex: number;
  50. /**
  51. * The exclusive end index, you have to render the primitive instances until you reach this one, but don't render this one!
  52. */
  53. partDataEndIndex: number;
  54. /**
  55. * The set of primitives to render is opaque.
  56. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  57. */
  58. public static get RenderModeOpaque(): number {
  59. return Render2DContext._renderModeOpaque;
  60. }
  61. /**
  62. * The set of primitives to render is using Alpha Test (aka masking).
  63. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  64. */
  65. public static get RenderModeAlphaTest(): number {
  66. return Render2DContext._renderModeAlphaTest;
  67. }
  68. /**
  69. * The set of primitives to render is transparent.
  70. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  71. */
  72. public static get RenderModeTransparent(): number {
  73. return Render2DContext._renderModeTransparent;
  74. }
  75. private static _renderModeOpaque: number = 1;
  76. private static _renderModeAlphaTest: number = 2;
  77. private static _renderModeTransparent: number = 3;
  78. private _renderMode: number;
  79. }
  80. /**
  81. * This class store information for the pointerEventObservable Observable.
  82. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  83. */
  84. export class PrimitivePointerInfo {
  85. private static _pointerOver = 0x0001;
  86. private static _pointerEnter = 0x0002;
  87. private static _pointerDown = 0x0004;
  88. private static _pointerMouseWheel = 0x0008;
  89. private static _pointerMove = 0x0010;
  90. private static _pointerUp = 0x0020;
  91. private static _pointerOut = 0x0040;
  92. private static _pointerLeave = 0x0080;
  93. private static _pointerGotCapture = 0x0100;
  94. private static _pointerLostCapture = 0x0200;
  95. private static _mouseWheelPrecision = 3.0;
  96. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  97. /**
  98. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  99. * Bubbles: yes
  100. */
  101. public static get PointerOver(): number {
  102. return PrimitivePointerInfo._pointerOver;
  103. }
  104. /**
  105. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  106. * Bubbles: no
  107. */
  108. public static get PointerEnter(): number {
  109. return PrimitivePointerInfo._pointerEnter;
  110. }
  111. /**
  112. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  113. * Bubbles: yes
  114. */
  115. public static get PointerDown(): number {
  116. return PrimitivePointerInfo._pointerDown;
  117. }
  118. /**
  119. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  120. * Bubbles: yes
  121. */
  122. public static get PointerMouseWheel(): number {
  123. return PrimitivePointerInfo._pointerMouseWheel;
  124. }
  125. /**
  126. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  127. * Bubbles: yes
  128. */
  129. public static get PointerMove(): number {
  130. return PrimitivePointerInfo._pointerMove;
  131. }
  132. /**
  133. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  134. * Bubbles: yes
  135. */
  136. public static get PointerUp(): number {
  137. return PrimitivePointerInfo._pointerUp;
  138. }
  139. /**
  140. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  141. * Bubbles: yes
  142. */
  143. public static get PointerOut(): number {
  144. return PrimitivePointerInfo._pointerOut;
  145. }
  146. /**
  147. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  148. * Bubbles: no
  149. */
  150. public static get PointerLeave(): number {
  151. return PrimitivePointerInfo._pointerLeave;
  152. }
  153. /**
  154. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  155. * Bubbles: yes
  156. */
  157. public static get PointerGotCapture(): number {
  158. return PrimitivePointerInfo._pointerGotCapture;
  159. }
  160. /**
  161. * This event type is raised after pointer capture is released for a pointer.
  162. * Bubbles: yes
  163. */
  164. public static get PointerLostCapture(): number {
  165. return PrimitivePointerInfo._pointerLostCapture;
  166. }
  167. public static get MouseWheelPrecision(): number {
  168. return PrimitivePointerInfo._mouseWheelPrecision;
  169. }
  170. /**
  171. * Event Type, one of the static PointerXXXX property defined above (PrimitivePointerInfo.PointerOver to PrimitivePointerInfo.PointerLostCapture)
  172. */
  173. eventType: number;
  174. /**
  175. * Position of the pointer relative to the bottom/left of the Canvas
  176. */
  177. canvasPointerPos: Vector2;
  178. /**
  179. * Position of the pointer relative to the bottom/left of the primitive that registered the Observer
  180. */
  181. primitivePointerPos: Vector2;
  182. /**
  183. * The primitive where the event was initiated first (in case of bubbling)
  184. */
  185. relatedTarget: Prim2DBase;
  186. /**
  187. * Position of the pointer relative to the bottom/left of the relatedTarget
  188. */
  189. relatedTargetPointerPos: Vector2;
  190. /**
  191. * An observable can set this property to true to stop bubbling on the upper levels
  192. */
  193. cancelBubble: boolean;
  194. /**
  195. * True if the Control keyboard key is down
  196. */
  197. ctrlKey: boolean;
  198. /**
  199. * true if the Shift keyboard key is down
  200. */
  201. shiftKey: boolean;
  202. /**
  203. * true if the Alt keyboard key is down
  204. */
  205. altKey: boolean;
  206. /**
  207. * true if the Meta keyboard key is down
  208. */
  209. metaKey: boolean;
  210. /**
  211. * For button, buttons, refer to https://www.w3.org/TR/pointerevents/#button-states
  212. */
  213. button: number;
  214. /**
  215. * For button, buttons, refer to https://www.w3.org/TR/pointerevents/#button-states
  216. */
  217. buttons: number;
  218. /**
  219. * The amount of mouse wheel rolled
  220. */
  221. mouseWheelDelta: number;
  222. /**
  223. * Id of the Pointer involved in the event
  224. */
  225. pointerId: number;
  226. width: number;
  227. height: number;
  228. presssure: number;
  229. tilt: Vector2;
  230. /**
  231. * true if the involved pointer is captured for a particular primitive, false otherwise.
  232. */
  233. isCaptured: boolean;
  234. constructor() {
  235. this.primitivePointerPos = Vector2.Zero();
  236. this.tilt = Vector2.Zero();
  237. this.cancelBubble = false;
  238. }
  239. updateRelatedTarget(prim: Prim2DBase, primPointerPos: Vector2) {
  240. this.relatedTarget = prim;
  241. this.relatedTargetPointerPos = primPointerPos;
  242. }
  243. public static getEventTypeName(mask: number): string {
  244. switch (mask) {
  245. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  246. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  247. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  248. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  249. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  250. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  251. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  252. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  253. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  254. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  255. }
  256. }
  257. }
  258. /**
  259. * Defines the horizontal and vertical alignment information for a Primitive.
  260. */
  261. export class PrimitiveAlignment {
  262. constructor(changeCallback: () => void) {
  263. this._changedCallback = changeCallback;
  264. this._horizontal = PrimitiveAlignment.AlignLeft;
  265. this._vertical = PrimitiveAlignment.AlignBottom;
  266. }
  267. /**
  268. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  269. */
  270. public static get AlignLeft(): number { return PrimitiveAlignment._AlignLeft; }
  271. /**
  272. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  273. */
  274. public static get AlignTop(): number { return PrimitiveAlignment._AlignTop; }
  275. /**
  276. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  277. */
  278. public static get AlignRight(): number { return PrimitiveAlignment._AlignRight; }
  279. /**
  280. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  281. */
  282. public static get AlignBottom(): number { return PrimitiveAlignment._AlignBottom; }
  283. /**
  284. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  285. */
  286. public static get AlignCenter(): number { return PrimitiveAlignment._AlignCenter; }
  287. /**
  288. * The content is stretched toward the opposite edges of the Primitive
  289. */
  290. public static get AlignStretch(): number { return PrimitiveAlignment._AlignStretch; }
  291. private static _AlignLeft = 1;
  292. private static _AlignTop = 1; // Same as left
  293. private static _AlignRight = 2;
  294. private static _AlignBottom = 2; // Same as right
  295. private static _AlignCenter = 3;
  296. private static _AlignStretch = 4;
  297. /**
  298. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  299. */
  300. public get horizontal(): number {
  301. return this._horizontal;
  302. }
  303. public set horizontal(value: number) {
  304. if (this._horizontal === value) {
  305. return;
  306. }
  307. this._horizontal = value;
  308. this._changedCallback();
  309. }
  310. /**
  311. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  312. */
  313. public get vertical(): number {
  314. return this._vertical;
  315. }
  316. public set vertical(value: number) {
  317. if (this._vertical === value) {
  318. return;
  319. }
  320. this._vertical = value;
  321. this._changedCallback();
  322. }
  323. private _changedCallback: () => void;
  324. private _horizontal: number;
  325. private _vertical: number;
  326. /**
  327. * Set the horizontal alignment from a string value.
  328. * @param text can be either: 'left','right','center','stretch'
  329. */
  330. setHorizontal(text: string) {
  331. let v = text.trim().toLocaleLowerCase();
  332. switch (v) {
  333. case "left":
  334. this.horizontal = PrimitiveAlignment.AlignLeft;
  335. return;
  336. case "right":
  337. this.horizontal = PrimitiveAlignment.AlignRight;
  338. return;
  339. case "center":
  340. this.horizontal = PrimitiveAlignment.AlignCenter;
  341. return;
  342. case "stretch":
  343. this.horizontal = PrimitiveAlignment.AlignStretch;
  344. return;
  345. }
  346. }
  347. /**
  348. * Set the vertical alignment from a string value.
  349. * @param text can be either: 'top','bottom','center','stretch'
  350. */
  351. setVertical(text: string) {
  352. let v = text.trim().toLocaleLowerCase();
  353. switch (v) {
  354. case "top":
  355. this.vertical = PrimitiveAlignment.AlignTop;
  356. return;
  357. case "bottom":
  358. this.vertical = PrimitiveAlignment.AlignBottom;
  359. return;
  360. case "center":
  361. this.vertical = PrimitiveAlignment.AlignCenter;
  362. return;
  363. case "stretch":
  364. this.vertical = PrimitiveAlignment.AlignStretch;
  365. return;
  366. }
  367. }
  368. /**
  369. * Set the horizontal and or vertical alignments from a string value.
  370. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  371. */
  372. fromString(value: string) {
  373. let m = value.trim().split(",");
  374. for (let v of m) {
  375. v = v.toLocaleLowerCase().trim();
  376. // Horizontal
  377. let i = v.indexOf("h:");
  378. if (i === -1) {
  379. i = v.indexOf("horizontal:");
  380. }
  381. if (i !== -1) {
  382. v = v.substr(v.indexOf(":") + 1);
  383. this.setHorizontal(v);
  384. continue;
  385. }
  386. // Vertical
  387. i = v.indexOf("v:");
  388. if (i === -1) {
  389. i = v.indexOf("vertical:");
  390. }
  391. if (i !== -1) {
  392. v = v.substr(v.indexOf(":") + 1);
  393. this.setVertical(v);
  394. continue;
  395. }
  396. }
  397. }
  398. }
  399. /**
  400. * Stores information about a Primitive that was intersected
  401. */
  402. export class PrimitiveIntersectedInfo {
  403. constructor(public prim: Prim2DBase, public intersectionLocation: Vector2) {
  404. }
  405. }
  406. /**
  407. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  408. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  409. */
  410. export class PrimitiveThickness {
  411. constructor(parentAccess: () => PrimitiveThickness, changedCallback: () => void) {
  412. this._parentAccess = parentAccess;
  413. this._changedCallback = changedCallback;
  414. this._pixels = new Array<number>(4);
  415. this._percentages = new Array<number>(4);
  416. this._setType(0, PrimitiveThickness.Auto);
  417. this._setType(1, PrimitiveThickness.Auto);
  418. this._setType(2, PrimitiveThickness.Auto);
  419. this._setType(3, PrimitiveThickness.Auto);
  420. this._pixels[0] = 0;
  421. this._pixels[1] = 0;
  422. this._pixels[2] = 0;
  423. this._pixels[3] = 0;
  424. }
  425. /**
  426. * Set the thickness from a string value
  427. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  428. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  429. */
  430. public fromString(thickness: string) {
  431. this._clear();
  432. let m = thickness.trim().split(",");
  433. // Special case, one value to apply to all edges
  434. if (m.length === 1 && thickness.indexOf(":") === -1) {
  435. this._setStringValue(m[0], 0, false);
  436. this._setStringValue(m[0], 1, false);
  437. this._setStringValue(m[0], 2, false);
  438. this._setStringValue(m[0], 3, false);
  439. this._changedCallback();
  440. return;
  441. }
  442. let res = false;
  443. for (let cm of m) {
  444. res = this._extractString(cm, false) || res;
  445. }
  446. if (!res) {
  447. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  448. }
  449. // Check the margin that weren't set and set them in auto
  450. if ((this._flags & 0x000F) === 0) this._flags |= PrimitiveThickness.Pixel << 0;
  451. if ((this._flags & 0x00F0) === 0) this._flags |= PrimitiveThickness.Pixel << 4;
  452. if ((this._flags & 0x0F00) === 0) this._flags |= PrimitiveThickness.Pixel << 8;
  453. if ((this._flags & 0xF000) === 0) this._flags |= PrimitiveThickness.Pixel << 12;
  454. this._changedCallback();
  455. }
  456. /**
  457. * Set the thickness from multiple string
  458. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  459. * @param top the top thickness to set
  460. * @param left the left thickness to set
  461. * @param right the right thickness to set
  462. * @param bottom the bottom thickness to set
  463. */
  464. public fromStrings(top: string, left: string, right: string, bottom: string): PrimitiveThickness {
  465. this._clear();
  466. this._setStringValue(top, 0, false);
  467. this._setStringValue(left, 1, false);
  468. this._setStringValue(right, 2, false);
  469. this._setStringValue(bottom, 3, false);
  470. this._changedCallback();
  471. return this;
  472. }
  473. /**
  474. * Set the thickness from pixel values
  475. * @param top the top thickness in pixels to set
  476. * @param left the left thickness in pixels to set
  477. * @param right the right thickness in pixels to set
  478. * @param bottom the bottom thickness in pixels to set
  479. */
  480. public fromPixels(top: number, left: number, right: number, bottom: number): PrimitiveThickness {
  481. this._clear();
  482. this._pixels[0] = top;
  483. this._pixels[1] = left;
  484. this._pixels[2] = right;
  485. this._pixels[3] = bottom;
  486. this._changedCallback();
  487. return this;
  488. }
  489. /**
  490. * Apply the same pixel value to all edges
  491. * @param margin the value to set, in pixels.
  492. */
  493. public fromUniformPixels(margin: number): PrimitiveThickness {
  494. this._clear();
  495. this._pixels[0] = margin;
  496. this._pixels[1] = margin;
  497. this._pixels[2] = margin;
  498. this._pixels[3] = margin;
  499. this._changedCallback();
  500. return this;
  501. }
  502. /**
  503. * Set all edges in auto
  504. */
  505. public auto(): PrimitiveThickness {
  506. this._clear();
  507. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  508. this._pixels[0] = 0;
  509. this._pixels[1] = 0;
  510. this._pixels[2] = 0;
  511. this._pixels[3] = 0;
  512. this._changedCallback();
  513. return this;
  514. }
  515. private _clear() {
  516. this._flags = 0;
  517. this._pixels[0] = 0;
  518. this._pixels[1] = 0;
  519. this._pixels[2] = 0;
  520. this._pixels[3] = 0;
  521. this._percentages[0] = null;
  522. this._percentages[1] = null;
  523. this._percentages[2] = null;
  524. this._percentages[3] = null;
  525. }
  526. private _extractString(value: string, emitChanged: boolean): boolean {
  527. let v = value.trim().toLocaleLowerCase();
  528. if (v.indexOf("top:") === 0) {
  529. v = v.substr(4).trim();
  530. return this._setStringValue(v, 0, emitChanged);
  531. }
  532. if (v.indexOf("left:") === 0) {
  533. v = v.substr(5).trim();
  534. return this._setStringValue(v, 1, emitChanged);
  535. }
  536. if (v.indexOf("right:") === 0) {
  537. v = v.substr(6).trim();
  538. return this._setStringValue(v, 2, emitChanged);
  539. }
  540. if (v.indexOf("bottom:") === 0) {
  541. v = v.substr(7).trim();
  542. return this._setStringValue(v, 3, emitChanged);
  543. }
  544. return false;
  545. }
  546. private _setStringValue(value: string, index: number, emitChanged: boolean): boolean {
  547. // Check for auto
  548. let v = value.trim().toLocaleLowerCase();
  549. if (v === "auto") {
  550. if (this._isType(index, PrimitiveThickness.Auto)) {
  551. return true;
  552. }
  553. this._setType(index, PrimitiveThickness.Auto);
  554. this._pixels[index] = 0;
  555. if (emitChanged) {
  556. this._changedCallback();
  557. }
  558. } else if (v === "inherit") {
  559. if (this._isType(index, PrimitiveThickness.Inherit)) {
  560. return true;
  561. }
  562. this._setType(index, PrimitiveThickness.Inherit);
  563. this._pixels[index] = null;
  564. if (emitChanged) {
  565. this._changedCallback();
  566. }
  567. } else {
  568. let pI = v.indexOf("%");
  569. // Check for percentage
  570. if (pI !== -1) {
  571. let n = v.substr(0, pI);
  572. let number = Math.round(Number(n)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  573. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number)) {
  574. return true;
  575. }
  576. this._setType(index, PrimitiveThickness.Percentage);
  577. if (isNaN(number)) {
  578. return false;
  579. }
  580. this._percentages[index] = number;
  581. if (emitChanged) {
  582. this._changedCallback();
  583. }
  584. return true;
  585. }
  586. // Check for pixel
  587. let n: string;
  588. pI = v.indexOf("px");
  589. if (pI !== -1) {
  590. n = v.substr(0, pI).trim();
  591. } else {
  592. n = v;
  593. }
  594. let number = Number(n);
  595. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  596. return true;
  597. }
  598. if (isNaN(number)) {
  599. return false;
  600. }
  601. this._pixels[index] = number;
  602. this._setType(index, PrimitiveThickness.Pixel);
  603. if (emitChanged) {
  604. this._changedCallback();
  605. }
  606. return true;
  607. }
  608. }
  609. private _setPixels(value: number, index: number, emitChanged: boolean) {
  610. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  611. value = Math.round(value);
  612. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  613. return;
  614. }
  615. this._setType(index, PrimitiveThickness.Pixel);
  616. this._pixels[index] = value;
  617. if (emitChanged) {
  618. this._changedCallback();
  619. }
  620. }
  621. private _setPercentage(value: number, index: number, emitChanged: boolean) {
  622. // Clip Value to bounds
  623. value = Math.min(1, value);
  624. value = Math.max(0, value);
  625. value = Math.round(value * 100) / 100; // 0.01 precision
  626. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  627. return;
  628. }
  629. this._setType(index, PrimitiveThickness.Percentage);
  630. this._percentages[index] = value;
  631. if (emitChanged) {
  632. this._changedCallback();
  633. }
  634. }
  635. private _getStringValue(index: number): string {
  636. let f = (this._flags >> (index * 4)) & 0xF;
  637. switch (f) {
  638. case PrimitiveThickness.Auto:
  639. return "auto";
  640. case PrimitiveThickness.Pixel:
  641. return `${this._pixels[index]}px`;
  642. case PrimitiveThickness.Percentage:
  643. return `${this._percentages[index] * 100}%`;
  644. case PrimitiveThickness.Inherit:
  645. return "inherit";
  646. }
  647. return "";
  648. }
  649. private _isType(index: number, type: number): boolean {
  650. let f = (this._flags >> (index * 4)) & 0xF;
  651. return f === type;
  652. }
  653. private _getType(index: number, processInherit: boolean): number {
  654. let t = (this._flags >> (index * 4)) & 0xF;
  655. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  656. let p = this._parentAccess();
  657. if (p) {
  658. return p._getType(index, true);
  659. }
  660. return PrimitiveThickness.Auto;
  661. }
  662. return t;
  663. }
  664. private _setType(index: number, type: number) {
  665. this._flags &= ~(0xF << (index * 4));
  666. this._flags |= type << (index * 4);
  667. }
  668. public setTop(value: number | string) {
  669. if (typeof value === "string") {
  670. this._setStringValue(value, 0, true);
  671. } else {
  672. this.topPixels = value;
  673. }
  674. }
  675. public setLeft(value: number | string) {
  676. if (typeof value === "string") {
  677. this._setStringValue(value, 1, true);
  678. } else {
  679. this.leftPixels = value;
  680. }
  681. }
  682. public setRight(value: number | string) {
  683. if (typeof value === "string") {
  684. this._setStringValue(value, 2, true);
  685. } else {
  686. this.rightPixels = value;
  687. }
  688. }
  689. public setBottom(value: number | string) {
  690. if (typeof value === "string") {
  691. this._setStringValue(value, 3, true);
  692. } else {
  693. this.bottomPixels = value;
  694. }
  695. }
  696. /**
  697. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  698. */
  699. public get top(): string {
  700. return this._getStringValue(0);
  701. }
  702. public set top(value: string) {
  703. this._setStringValue(value, 0, true);
  704. }
  705. /**
  706. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  707. */
  708. public get left(): string {
  709. return this._getStringValue(1);
  710. }
  711. public set left(value: string) {
  712. this._setStringValue(value, 1, true);
  713. }
  714. /**
  715. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  716. */
  717. public get right(): string {
  718. return this._getStringValue(2);
  719. }
  720. public set right(value: string) {
  721. this._setStringValue(value, 2, true);
  722. }
  723. /**
  724. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  725. */
  726. public get bottom(): string {
  727. return this._getStringValue(3);
  728. }
  729. public set bottom(value: string) {
  730. this._setStringValue(value, 3, true);
  731. }
  732. /**
  733. * Get/set the top thickness in pixel.
  734. */
  735. public get topPixels(): number {
  736. return this._pixels[0];
  737. }
  738. public set topPixels(value: number) {
  739. this._setPixels(value, 0, true);
  740. }
  741. /**
  742. * Get/set the left thickness in pixel.
  743. */
  744. public get leftPixels(): number {
  745. return this._pixels[1];
  746. }
  747. public set leftPixels(value: number) {
  748. this._setPixels(value, 1, true);
  749. }
  750. /**
  751. * Get/set the right thickness in pixel.
  752. */
  753. public get rightPixels(): number {
  754. return this._pixels[2];
  755. }
  756. public set rightPixels(value: number) {
  757. this._setPixels(value, 2, true);
  758. }
  759. /**
  760. * Get/set the bottom thickness in pixel.
  761. */
  762. public get bottomPixels(): number {
  763. return this._pixels[3];
  764. }
  765. public set bottomPixels(value: number) {
  766. this._setPixels(value, 3, true);
  767. }
  768. /**
  769. * Get/set the top thickness in percentage.
  770. * The get will return a valid value only if the edge type is percentage.
  771. * The Set will change the edge mode if needed
  772. */
  773. public get topPercentage(): number {
  774. return this._percentages[0];
  775. }
  776. public set topPercentage(value: number) {
  777. this._setPercentage(value, 0, true);
  778. }
  779. /**
  780. * Get/set the left thickness in percentage.
  781. * The get will return a valid value only if the edge mode is percentage.
  782. * The Set will change the edge mode if needed
  783. */
  784. public get leftPercentage(): number {
  785. return this._percentages[1];
  786. }
  787. public set leftPercentage(value: number) {
  788. this._setPercentage(value, 1, true);
  789. }
  790. /**
  791. * Get/set the right thickness in percentage.
  792. * The get will return a valid value only if the edge mode is percentage.
  793. * The Set will change the edge mode if needed
  794. */
  795. public get rightPercentage(): number {
  796. return this._percentages[2];
  797. }
  798. public set rightPercentage(value: number) {
  799. this._setPercentage(value, 2, true);
  800. }
  801. /**
  802. * Get/set the bottom thickness in percentage.
  803. * The get will return a valid value only if the edge mode is percentage.
  804. * The Set will change the edge mode if needed
  805. */
  806. public get bottomPercentage(): number {
  807. return this._percentages[3];
  808. }
  809. public set bottomPercentage(value: number) {
  810. this._setPercentage(value, 3, true);
  811. }
  812. /**
  813. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  814. */
  815. public get topMode(): number {
  816. return this._getType(0, false);
  817. }
  818. public set topMode(mode: number) {
  819. this._setType(0, mode);
  820. }
  821. /**
  822. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  823. */
  824. public get leftMode(): number {
  825. return this._getType(1, false);
  826. }
  827. public set leftMode(mode: number) {
  828. this._setType(1, mode);
  829. }
  830. /**
  831. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  832. */
  833. public get rightMode(): number {
  834. return this._getType(2, false);
  835. }
  836. public set rightMode(mode: number) {
  837. this._setType(2, mode);
  838. }
  839. /**
  840. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  841. */
  842. public get bottomMode(): number {
  843. return this._getType(3, false);
  844. }
  845. public set bottomMode(mode: number) {
  846. this._setType(3, mode);
  847. }
  848. private _parentAccess: () => PrimitiveThickness;
  849. private _changedCallback: () => void;
  850. private _pixels: number[];
  851. private _percentages: number[]; // Percentages are in fact stored in a normalized range [0;1] with a 0.01 precision
  852. private _flags: number;
  853. public static Auto = 0x1;
  854. public static Inherit = 0x2;
  855. public static Percentage = 0x4;
  856. public static Pixel = 0x8;
  857. private _computePixels(index: number, sourceArea: Size, emitChanged: boolean) {
  858. let type = this._getType(index, false);
  859. if (type === PrimitiveThickness.Inherit) {
  860. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  861. return;
  862. }
  863. if (type !== PrimitiveThickness.Percentage) {
  864. return;
  865. }
  866. let pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  867. this._pixels[index] = pixels;
  868. if (emitChanged) {
  869. this._changedCallback();
  870. }
  871. }
  872. /**
  873. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  874. * @param sourceArea the source area
  875. * @param contentSize the content size to position/resize
  876. * @param alignment the alignment setting
  877. * @param dstOffset the position of the content
  878. * @param dstArea the new size of the content
  879. */
  880. public computeWithAlignment(sourceArea: Size, contentSize: Size, alignment: PrimitiveAlignment, dstOffset: Vector2, dstArea: Size) {
  881. // Fetch some data
  882. let topType = this._getType(0, true);
  883. let leftType = this._getType(1, true);
  884. let rightType = this._getType(2, true);
  885. let bottomType = this._getType(3, true);
  886. let hasWidth = contentSize && (contentSize.width != null);
  887. let hasHeight = contentSize && (contentSize.height != null);
  888. let width = hasWidth ? contentSize.width : 0;
  889. let height = hasHeight ? contentSize.height : 0;
  890. let isTopAuto = topType === PrimitiveThickness.Auto;
  891. let isLeftAuto = leftType === PrimitiveThickness.Auto;
  892. let isRightAuto = rightType === PrimitiveThickness.Auto;
  893. let isBottomAuto = bottomType === PrimitiveThickness.Auto;
  894. switch (alignment.horizontal) {
  895. case PrimitiveAlignment.AlignLeft:
  896. {
  897. if (isLeftAuto) {
  898. dstOffset.x = 0;
  899. } else {
  900. this._computePixels(1, sourceArea, true);
  901. dstOffset.x = this.leftPixels;
  902. }
  903. dstArea.width = width;
  904. break;
  905. }
  906. case PrimitiveAlignment.AlignRight:
  907. {
  908. if (isRightAuto) {
  909. dstOffset.x = Math.round(sourceArea.width - width);
  910. } else {
  911. this._computePixels(2, sourceArea, true);
  912. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  913. }
  914. dstArea.width = width;
  915. break;
  916. }
  917. case PrimitiveAlignment.AlignStretch:
  918. {
  919. if (isLeftAuto) {
  920. dstOffset.x = 0;
  921. } else {
  922. this._computePixels(1, sourceArea, true);
  923. dstOffset.x = this.leftPixels;
  924. }
  925. let right = 0;
  926. if (!isRightAuto) {
  927. this._computePixels(2, sourceArea, true);
  928. right = this.rightPixels;
  929. }
  930. dstArea.width = sourceArea.width - (dstOffset.x + right);
  931. break;
  932. }
  933. case PrimitiveAlignment.AlignCenter:
  934. {
  935. if (!isLeftAuto) {
  936. this._computePixels(1, sourceArea, true);
  937. }
  938. if (!isRightAuto) {
  939. this._computePixels(2, sourceArea, true);
  940. }
  941. let offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  942. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  943. dstArea.width = width;
  944. break;
  945. }
  946. }
  947. switch (alignment.vertical) {
  948. case PrimitiveAlignment.AlignTop:
  949. {
  950. if (isTopAuto) {
  951. dstOffset.y = sourceArea.height - height;
  952. } else {
  953. this._computePixels(0, sourceArea, true);
  954. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  955. }
  956. dstArea.height = height;
  957. break;
  958. }
  959. case PrimitiveAlignment.AlignBottom:
  960. {
  961. if (isBottomAuto) {
  962. dstOffset.y = 0;
  963. } else {
  964. this._computePixels(3, sourceArea, true);
  965. dstOffset.y = this.bottomPixels;
  966. }
  967. dstArea.height = height;
  968. break;
  969. }
  970. case PrimitiveAlignment.AlignStretch:
  971. {
  972. if (isBottomAuto) {
  973. dstOffset.y = 0;
  974. } else {
  975. this._computePixels(3, sourceArea, true);
  976. dstOffset.y = this.bottomPixels;
  977. }
  978. let top = 0;
  979. if (!isTopAuto) {
  980. this._computePixels(0, sourceArea, true);
  981. top = this.topPixels;
  982. }
  983. dstArea.height = sourceArea.height - (dstOffset.y + top);
  984. break;
  985. }
  986. case PrimitiveAlignment.AlignCenter:
  987. {
  988. if (!isTopAuto) {
  989. this._computePixels(0, sourceArea, true);
  990. }
  991. if (!isBottomAuto) {
  992. this._computePixels(3, sourceArea, true);
  993. }
  994. let offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  995. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  996. dstArea.height = height;
  997. break;
  998. }
  999. }
  1000. }
  1001. /**
  1002. * Compute an area and its position considering this thickness properties based on a given source area
  1003. * @param sourceArea the source area
  1004. * @param dstOffset the position of the resulting area
  1005. * @param dstArea the size of the resulting area
  1006. */
  1007. public compute(sourceArea: Size, dstOffset: Vector2, dstArea: Size) {
  1008. this._computePixels(0, sourceArea, true);
  1009. this._computePixels(1, sourceArea, true);
  1010. this._computePixels(2, sourceArea, true);
  1011. this._computePixels(3, sourceArea, true);
  1012. dstOffset.x = this.leftPixels;
  1013. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  1014. dstOffset.y = this.bottomPixels;
  1015. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  1016. }
  1017. /**
  1018. * Compute an area considering this thickness properties based on a given source area
  1019. * @param sourceArea the source area
  1020. * @param result the resulting area
  1021. */
  1022. computeArea(sourceArea: Size, result: Size) {
  1023. this._computePixels(0, sourceArea, true);
  1024. this._computePixels(1, sourceArea, true);
  1025. this._computePixels(2, sourceArea, true);
  1026. this._computePixels(3, sourceArea, true);
  1027. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  1028. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  1029. }
  1030. enlarge(sourceArea: Size, dstOffset: Vector2, enlargedArea: Size) {
  1031. this._computePixels(0, sourceArea, true);
  1032. this._computePixels(1, sourceArea, true);
  1033. this._computePixels(2, sourceArea, true);
  1034. this._computePixels(3, sourceArea, true);
  1035. dstOffset.x = this.leftPixels;
  1036. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  1037. dstOffset.y = this.bottomPixels;
  1038. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  1039. }
  1040. }
  1041. /**
  1042. * Main class used for the Primitive Intersection API
  1043. */
  1044. export class IntersectInfo2D {
  1045. constructor() {
  1046. this.findFirstOnly = false;
  1047. this.intersectHidden = false;
  1048. this.pickPosition = Vector2.Zero();
  1049. }
  1050. // Input settings, to setup before calling an intersection related method
  1051. /**
  1052. * Set the pick position, relative to the primitive where the intersection test is made
  1053. */
  1054. public pickPosition: Vector2;
  1055. /**
  1056. * If true the intersection will stop at the first hit, if false all primitives will be tested and the intersectedPrimitives array will be filled accordingly (false default)
  1057. */
  1058. public findFirstOnly: boolean;
  1059. /**
  1060. * If true the intersection test will also be made on hidden primitive (false default)
  1061. */
  1062. public intersectHidden: boolean;
  1063. // Intermediate data, don't use!
  1064. public _globalPickPosition: Vector2;
  1065. public _localPickPosition: Vector2;
  1066. // Output settings, up to date in return of a call to an intersection related method
  1067. /**
  1068. * The topmost intersected primitive
  1069. */
  1070. public topMostIntersectedPrimitive: PrimitiveIntersectedInfo;
  1071. /**
  1072. * The array containing all intersected primitive, in no particular order.
  1073. */
  1074. public intersectedPrimitives: Array<PrimitiveIntersectedInfo>;
  1075. /**
  1076. * true if at least one primitive intersected during the test
  1077. */
  1078. public get isIntersected(): boolean {
  1079. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  1080. }
  1081. public isPrimIntersected(prim: Prim2DBase): Vector2 {
  1082. for (let cur of this.intersectedPrimitives) {
  1083. if (cur.prim === prim) {
  1084. return cur.intersectionLocation;
  1085. }
  1086. }
  1087. return null;
  1088. }
  1089. // Internals, don't use
  1090. public _exit(firstLevel: boolean) {
  1091. if (firstLevel) {
  1092. this._globalPickPosition = null;
  1093. }
  1094. }
  1095. }
  1096. @className("Prim2DBase")
  1097. /**
  1098. * Base class for a Primitive of the Canvas2D feature
  1099. */
  1100. export class Prim2DBase extends SmartPropertyPrim {
  1101. static PRIM2DBASE_PROPCOUNT: number = 16;
  1102. public static _bigInt = Math.pow(2, 30);
  1103. constructor(settings: {
  1104. parent ?: Prim2DBase,
  1105. id ?: string,
  1106. children ?: Array<Prim2DBase>,
  1107. position ?: Vector2,
  1108. x ?: number,
  1109. y ?: number,
  1110. rotation ?: number,
  1111. scale ?: number,
  1112. scaleX ?: number,
  1113. scaleY ?: number,
  1114. opacity ?: number,
  1115. zOrder ?: number,
  1116. origin ?: Vector2,
  1117. layoutEngine ?: LayoutEngineBase | string,
  1118. isVisible ?: boolean,
  1119. childrenFlatZOrder?: boolean,
  1120. marginTop ?: number | string,
  1121. marginLeft ?: number | string,
  1122. marginRight ?: number | string,
  1123. marginBottom ?: number | string,
  1124. margin ?: number | string,
  1125. marginHAlignment ?: number,
  1126. marginVAlignment ?: number,
  1127. marginAlignment ?: string,
  1128. paddingTop ?: number | string,
  1129. paddingLeft ?: number | string,
  1130. paddingRight ?: number | string,
  1131. paddingBottom ?: number | string,
  1132. padding ?: string,
  1133. }) {
  1134. // Avoid checking every time if the object exists
  1135. if (settings == null) {
  1136. settings = {};
  1137. }
  1138. // BASE CLASS CALL
  1139. super();
  1140. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  1141. let owner: Canvas2D;
  1142. let parent: Prim2DBase;
  1143. if (Prim2DBase._isCanvasInit) {
  1144. owner = <Canvas2D><any>this;
  1145. parent = null;
  1146. this._canvasPreInit(settings);
  1147. } else {
  1148. if (settings.parent != null) {
  1149. parent = settings.parent;
  1150. owner = settings.parent.owner;
  1151. if (!owner) {
  1152. throw new Error(`Parent ${parent.id} of ${settings.id} doesn't have a valid owner!`);
  1153. }
  1154. if (!(this instanceof Group2D) && !(this instanceof Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  1155. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  1156. }
  1157. }
  1158. }
  1159. // Fields initialization
  1160. this._layoutEngine = CanvasLayoutEngine.Singleton;
  1161. this._size = null; //Size.Zero();
  1162. this._scale = new Vector2(1, 1);
  1163. this._actualSize = null;
  1164. this._boundingSize = Size.Zero();
  1165. this._layoutArea = Size.Zero();
  1166. this._layoutAreaPos = Vector2.Zero();
  1167. this._marginOffset = Vector2.Zero();
  1168. this._paddingOffset = Vector2.Zero();
  1169. this._parentPaddingOffset = Vector2.Zero();
  1170. this._parentContentArea = Size.Zero();
  1171. this._lastAutoSizeArea = Size.Zero();
  1172. this._contentArea = new Size(null, null);
  1173. this._pointerEventObservable = new Observable<PrimitivePointerInfo>();
  1174. this._boundingInfo = new BoundingInfo2D();
  1175. this._owner = owner;
  1176. this._parent = null;
  1177. this._margin = null;
  1178. this._padding = null;
  1179. this._marginAlignment = null;
  1180. this._id = settings.id;
  1181. this.propertyChanged = new Observable<PropertyChangedInfo>();
  1182. this._children = new Array<Prim2DBase>();
  1183. this._localTransform = new Matrix();
  1184. this._globalTransform = null;
  1185. this._invGlobalTransform = null;
  1186. this._globalTransformProcessStep = 0;
  1187. this._globalTransformStep = 0;
  1188. this._renderGroup = null;
  1189. this._primLinearPosition = 0;
  1190. this._manualZOrder = null;
  1191. this._zOrder = 0;
  1192. this._zMax = 0;
  1193. this._firstZDirtyIndex = Prim2DBase._bigInt;
  1194. this._setFlags(SmartPropertyPrim.flagIsPickable | SmartPropertyPrim.flagBoundingInfoDirty | SmartPropertyPrim.flagActualOpacityDirty);
  1195. if (settings.opacity != null) {
  1196. this._opacity = settings.opacity;
  1197. } else {
  1198. this._opacity = 1;
  1199. }
  1200. this._updateRenderMode();
  1201. if (settings.childrenFlatZOrder) {
  1202. this._setFlags(SmartPropertyPrim.flagChildrenFlatZOrder);
  1203. }
  1204. // If the parent is given, initialize the hierarchy/owner related data
  1205. if (parent != null) {
  1206. parent.addChild(this);
  1207. this._patchHierarchy(parent.owner);
  1208. }
  1209. // If it's a group, detect its own states
  1210. if (this.owner && this instanceof Group2D) {
  1211. var group: any = this;
  1212. group.detectGroupStates();
  1213. }
  1214. // Time to insert children if some are specified
  1215. if (settings.children != null) {
  1216. for (let child of settings.children) {
  1217. this.addChild(child);
  1218. // Good time to patch the hierarchy, it won't go very far if there's no need to
  1219. if (this.owner != null) {
  1220. child._patchHierarchy(this.owner);
  1221. }
  1222. }
  1223. }
  1224. if (settings.zOrder != null) {
  1225. this.zOrder = settings.zOrder;
  1226. }
  1227. // Set the model related properties
  1228. if (settings.position != null) {
  1229. this.position = settings.position;
  1230. }
  1231. else if (settings.x != null || settings.y != null) {
  1232. this.position = new Vector2(settings.x || 0, settings.y || 0);
  1233. } else {
  1234. this._position = null;
  1235. }
  1236. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  1237. if (settings.scale != null) {
  1238. this.scale = settings.scale;
  1239. } else {
  1240. if (settings.scaleX != null) {
  1241. this.scaleX = settings.scaleX;
  1242. }
  1243. if (settings.scaleY != null) {
  1244. this.scaleY = settings.scaleY;
  1245. }
  1246. }
  1247. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  1248. this.origin = settings.origin || new Vector2(0.5, 0.5);
  1249. // Layout Engine
  1250. if (settings.layoutEngine != null) {
  1251. if (typeof settings.layoutEngine === "string") {
  1252. let name = (<string>settings.layoutEngine).toLocaleLowerCase().trim();
  1253. if (name === "canvas" || name === "canvaslayoutengine") {
  1254. this.layoutEngine = CanvasLayoutEngine.Singleton;
  1255. } else if (name.indexOf("stackpanel") === 0 || name.indexOf("horizontalstackpanel") === 0) {
  1256. this.layoutEngine = StackPanelLayoutEngine.Horizontal;
  1257. } else if (name.indexOf("verticalstackpanel") === 0) {
  1258. this.layoutEngine = StackPanelLayoutEngine.Vertical;
  1259. }
  1260. } else if (settings.layoutEngine instanceof LayoutEngineBase) {
  1261. this.layoutEngine = <LayoutEngineBase>settings.layoutEngine;
  1262. }
  1263. }
  1264. // Set the layout/margin stuffs
  1265. if (settings.marginTop) {
  1266. this.margin.setTop(settings.marginTop);
  1267. }
  1268. if (settings.marginLeft) {
  1269. this.margin.setLeft(settings.marginLeft);
  1270. }
  1271. if (settings.marginRight) {
  1272. this.margin.setRight(settings.marginRight);
  1273. }
  1274. if (settings.marginBottom) {
  1275. this.margin.setBottom(settings.marginBottom);
  1276. }
  1277. if (settings.margin) {
  1278. if (typeof settings.margin === "string") {
  1279. this.margin.fromString(<string>settings.margin);
  1280. } else {
  1281. this.margin.fromUniformPixels(<number>settings.margin);
  1282. }
  1283. }
  1284. if (settings.marginHAlignment) {
  1285. this.marginAlignment.horizontal = settings.marginHAlignment;
  1286. }
  1287. if (settings.marginVAlignment) {
  1288. this.marginAlignment.vertical = settings.marginVAlignment;
  1289. }
  1290. if (settings.marginAlignment) {
  1291. this.marginAlignment.fromString(settings.marginAlignment);
  1292. }
  1293. if (settings.paddingTop) {
  1294. this.padding.setTop(settings.paddingTop);
  1295. }
  1296. if (settings.paddingLeft) {
  1297. this.padding.setLeft(settings.paddingLeft);
  1298. }
  1299. if (settings.paddingRight) {
  1300. this.padding.setRight(settings.paddingRight);
  1301. }
  1302. if (settings.paddingBottom) {
  1303. this.padding.setBottom(settings.paddingBottom);
  1304. }
  1305. if (settings.padding) {
  1306. this.padding.fromString(settings.padding);
  1307. }
  1308. // Dirty layout and positioning
  1309. this._parentLayoutDirty();
  1310. this._positioningDirty();
  1311. }
  1312. public get actionManager(): ActionManager {
  1313. if (!this._actionManager) {
  1314. this._actionManager = new ActionManager(this.owner.scene);
  1315. }
  1316. return this._actionManager;
  1317. }
  1318. /**
  1319. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  1320. * @param predicate the predicate to test on each parent
  1321. * @return the first primitive where the predicate was successful
  1322. */
  1323. public traverseUp(predicate: (p: Prim2DBase) => boolean): Prim2DBase {
  1324. let p: Prim2DBase = this;
  1325. while (p != null) {
  1326. if (predicate(p)) {
  1327. return p;
  1328. }
  1329. p = p._parent;
  1330. }
  1331. return null;
  1332. }
  1333. /**
  1334. * Retrieve the owner Canvas2D
  1335. */
  1336. public get owner(): Canvas2D {
  1337. return this._owner;
  1338. }
  1339. /**
  1340. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  1341. */
  1342. public get parent(): Prim2DBase {
  1343. return this._parent;
  1344. }
  1345. /**
  1346. * The array of direct children primitives
  1347. */
  1348. public get children(): Prim2DBase[] {
  1349. return this._children;
  1350. }
  1351. /**
  1352. * The identifier of this primitive, may not be unique, it's for information purpose only
  1353. */
  1354. public get id(): string {
  1355. return this._id;
  1356. }
  1357. /**
  1358. * Metadata of the position property
  1359. */
  1360. public static positionProperty: Prim2DPropInfo;
  1361. /**
  1362. * Metadata of the actualPosition property
  1363. */
  1364. public static actualPositionProperty: Prim2DPropInfo;
  1365. /**
  1366. * Metadata of the size property
  1367. */
  1368. public static sizeProperty: Prim2DPropInfo;
  1369. /**
  1370. * Metadata of the rotation property
  1371. */
  1372. public static rotationProperty: Prim2DPropInfo;
  1373. /**
  1374. * Metadata of the scale property
  1375. */
  1376. public static scaleProperty: Prim2DPropInfo;
  1377. /**
  1378. * Metadata of the origin property
  1379. */
  1380. public static originProperty: Prim2DPropInfo;
  1381. /**
  1382. * Metadata of the levelVisible property
  1383. */
  1384. public static levelVisibleProperty: Prim2DPropInfo;
  1385. /**
  1386. * Metadata of the isVisible property
  1387. */
  1388. public static isVisibleProperty: Prim2DPropInfo;
  1389. /**
  1390. * Metadata of the zOrder property
  1391. */
  1392. public static zOrderProperty: Prim2DPropInfo;
  1393. /**
  1394. * Metadata of the margin property
  1395. */
  1396. public static marginProperty: Prim2DPropInfo;
  1397. /**
  1398. * Metadata of the margin property
  1399. */
  1400. public static paddingProperty: Prim2DPropInfo;
  1401. /**
  1402. * Metadata of the hAlignment property
  1403. */
  1404. public static marginAlignmentProperty: Prim2DPropInfo;
  1405. /**
  1406. * Metadata of the opacity property
  1407. */
  1408. public static opacityProperty: Prim2DPropInfo;
  1409. /**
  1410. * Metadata of the scaleX property
  1411. */
  1412. public static scaleXProperty: Prim2DPropInfo;
  1413. /**
  1414. * Metadata of the scaleY property
  1415. */
  1416. public static scaleYProperty: Prim2DPropInfo;
  1417. @instanceLevelProperty(1, pi => Prim2DBase.actualPositionProperty = pi, false, false, true)
  1418. /**
  1419. * Return the position where the primitive is rendered in the Canvas, this position may be different than the one returned by the position property due to layout/alignment/margin/padding computing
  1420. */
  1421. public get actualPosition(): Vector2 {
  1422. if (this._actualPosition != null) {
  1423. return this._actualPosition;
  1424. }
  1425. if (this._position != null) {
  1426. return this._position;
  1427. }
  1428. // At least return 0,0, we can't return null on actualPosition
  1429. return Prim2DBase._nullPosition;
  1430. }
  1431. private static _nullPosition = Vector2.Zero();
  1432. /**
  1433. * DO NOT INVOKE for internal purpose only
  1434. */
  1435. public set actualPosition(val: Vector2) {
  1436. this._actualPosition = val;
  1437. }
  1438. /**
  1439. * Shortcut to actualPosition.x
  1440. */
  1441. public get actualX(): number {
  1442. return this.actualPosition.x;
  1443. }
  1444. /**
  1445. * Shortcut to actualPosition.y
  1446. */
  1447. public get actualY(): number {
  1448. return this.actualPosition.y;
  1449. }
  1450. /**
  1451. * Position of the primitive, relative to its parent.
  1452. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  1453. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  1454. * Setting this property may have no effect is specific alignment are in effect.
  1455. */
  1456. @dynamicLevelProperty(2, pi => Prim2DBase.positionProperty = pi, false, false, true)
  1457. public get position(): Vector2 {
  1458. return this._position || Prim2DBase._nullPosition;
  1459. }
  1460. public set position(value: Vector2) {
  1461. if (!this._checkPositionChange()) {
  1462. return;
  1463. }
  1464. this._position = value;
  1465. this.markAsDirty("actualPosition");
  1466. }
  1467. /**
  1468. * Direct access to the position.x value of the primitive
  1469. * Use this property when you only want to change one component of the position property
  1470. */
  1471. public get x(): number {
  1472. if (!this._position) {
  1473. return null;
  1474. }
  1475. return this._position.x;
  1476. }
  1477. public set x(value: number) {
  1478. if (!this._checkPositionChange()) {
  1479. return;
  1480. }
  1481. if (!this._position) {
  1482. this._position = Vector2.Zero();
  1483. }
  1484. if (this._position.x === value) {
  1485. return;
  1486. }
  1487. this._position.x = value;
  1488. this.markAsDirty("position");
  1489. this.markAsDirty("actualPosition");
  1490. }
  1491. /**
  1492. * Direct access to the position.y value of the primitive
  1493. * Use this property when you only want to change one component of the position property
  1494. */
  1495. public get y(): number {
  1496. if (!this._position) {
  1497. return null;
  1498. }
  1499. return this._position.y;
  1500. }
  1501. public set y(value: number) {
  1502. if (!this._checkPositionChange()) {
  1503. return;
  1504. }
  1505. if (!this._position) {
  1506. this._position = Vector2.Zero();
  1507. }
  1508. if (this._position.y === value) {
  1509. return;
  1510. }
  1511. this._position.y = value;
  1512. this.markAsDirty("position");
  1513. this.markAsDirty("actualPosition");
  1514. }
  1515. private static boundinbBoxReentrency = false;
  1516. protected static nullSize = Size.Zero();
  1517. /**
  1518. * Size of the primitive or its bounding area
  1519. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  1520. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  1521. */
  1522. @dynamicLevelProperty(3, pi => Prim2DBase.sizeProperty = pi, false, true)
  1523. public get size(): Size {
  1524. if (!this._size || this._size.width == null || this._size.height == null) {
  1525. if (Prim2DBase.boundinbBoxReentrency) {
  1526. return Prim2DBase.nullSize;
  1527. }
  1528. if (!this._isFlagSet(SmartPropertyPrim.flagBoundingInfoDirty)) {
  1529. return this._boundingSize;
  1530. }
  1531. Prim2DBase.boundinbBoxReentrency = true;
  1532. let b = this.boundingInfo;
  1533. Prim2DBase.boundinbBoxReentrency = false;
  1534. return this._boundingSize;
  1535. }
  1536. return this._size;
  1537. }
  1538. public set size(value: Size) {
  1539. this._size = value;
  1540. }
  1541. /**
  1542. * Direct access to the size.width value of the primitive
  1543. * Use this property when you only want to change one component of the size property
  1544. */
  1545. public get width(): number {
  1546. if (!this.size) {
  1547. return null;
  1548. }
  1549. return this.size.width;
  1550. }
  1551. public set width(value: number) {
  1552. if (!this.size) {
  1553. this.size = new Size(value, 0);
  1554. return;
  1555. }
  1556. if (this.size.width === value) {
  1557. return;
  1558. }
  1559. this.size.width = value;
  1560. this.markAsDirty("size");
  1561. this._positioningDirty();
  1562. }
  1563. /**
  1564. * Direct access to the size.height value of the primitive
  1565. * Use this property when you only want to change one component of the size property
  1566. */
  1567. public get height(): number {
  1568. if (!this.size) {
  1569. return null;
  1570. }
  1571. return this.size.height;
  1572. }
  1573. public set height(value: number) {
  1574. if (!this.size) {
  1575. this.size = new Size(0, value);
  1576. return;
  1577. }
  1578. if (this.size.height === value) {
  1579. return;
  1580. }
  1581. this.size.height = value;
  1582. this.markAsDirty("size");
  1583. this._positioningDirty();
  1584. }
  1585. @instanceLevelProperty(4, pi => Prim2DBase.rotationProperty = pi, false, true)
  1586. /**
  1587. * Rotation of the primitive, in radian, along the Z axis
  1588. */
  1589. public get rotation(): number {
  1590. return this._rotation;
  1591. }
  1592. public set rotation(value: number) {
  1593. this._rotation = value;
  1594. }
  1595. @instanceLevelProperty(5, pi => Prim2DBase.scaleProperty = pi, false, true)
  1596. /**
  1597. * Uniform scale applied on the primitive. If a non-uniform scale is applied through scaleX/scaleY property the getter of this property will return scaleX.
  1598. */
  1599. public set scale(value: number) {
  1600. this._scale.x = this._scale.y = value;
  1601. }
  1602. public get scale(): number {
  1603. return this._scale.x;
  1604. }
  1605. /**
  1606. * Return the size of the primitive as it's being rendered into the target.
  1607. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  1608. * BEWARE: don't use the setter, it's for internal purpose only
  1609. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  1610. */
  1611. public get actualSize(): Size {
  1612. if (this._actualSize) {
  1613. return this._actualSize;
  1614. }
  1615. return this._size;
  1616. }
  1617. public set actualSize(value: Size) {
  1618. if (this._actualSize.equals(value)) {
  1619. return;
  1620. }
  1621. this._actualSize = value;
  1622. }
  1623. public get actualZOffset(): number {
  1624. if (this._manualZOrder!=null) {
  1625. return this._manualZOrder;
  1626. }
  1627. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  1628. this._updateZOrder();
  1629. }
  1630. return (1 - this._zOrder);
  1631. }
  1632. /**
  1633. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  1634. * The Primitive's size won't be less than specified.
  1635. * The default value depends of the Primitive type
  1636. */
  1637. public get minSize(): Size {
  1638. return this._minSize;
  1639. }
  1640. public set minSize(value: Size) {
  1641. if (this._minSize && value && this._minSize.equals(value)) {
  1642. return;
  1643. }
  1644. this._minSize = value;
  1645. this._parentLayoutDirty();
  1646. }
  1647. /**
  1648. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  1649. * The Primitive's size won't be more than specified.
  1650. * The default value depends of the Primitive type
  1651. */
  1652. public get maxSize(): Size {
  1653. return this._maxSize;
  1654. }
  1655. public set maxSize(value: Size) {
  1656. if (this._maxSize && value && this._maxSize.equals(value)) {
  1657. return;
  1658. }
  1659. this._maxSize = value;
  1660. this._parentLayoutDirty();
  1661. }
  1662. /**
  1663. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  1664. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  1665. * For instance:
  1666. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  1667. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  1668. * 0,1 means the center is top/left
  1669. * @returns The normalized center.
  1670. */
  1671. @dynamicLevelProperty(6, pi => Prim2DBase.originProperty = pi, false, true)
  1672. public get origin(): Vector2 {
  1673. return this._origin;
  1674. }
  1675. public set origin(value: Vector2) {
  1676. this._origin = value;
  1677. }
  1678. @dynamicLevelProperty(7, pi => Prim2DBase.levelVisibleProperty = pi)
  1679. /**
  1680. * Let the user defines if the Primitive is hidden or not at its level. As Primitives inherit the hidden status from their parent, only the isVisible property give properly the real visible state.
  1681. * Default is true, setting to false will hide this primitive and its children.
  1682. */
  1683. public get levelVisible(): boolean {
  1684. return this._isFlagSet(SmartPropertyPrim.flagLevelVisible);
  1685. }
  1686. public set levelVisible(value: boolean) {
  1687. this._changeFlags(SmartPropertyPrim.flagLevelVisible, value);
  1688. }
  1689. @instanceLevelProperty(8, pi => Prim2DBase.isVisibleProperty = pi)
  1690. /**
  1691. * Use ONLY THE GETTER to determine if the primitive is visible or not.
  1692. * The Setter is for internal purpose only!
  1693. */
  1694. public get isVisible(): boolean {
  1695. return this._isFlagSet(SmartPropertyPrim.flagIsVisible);
  1696. }
  1697. public set isVisible(value: boolean) {
  1698. this._changeFlags(SmartPropertyPrim.flagIsVisible, value);
  1699. }
  1700. @instanceLevelProperty(9, pi => Prim2DBase.zOrderProperty = pi)
  1701. /**
  1702. * You can override the default Z Order through this property, but most of the time the default behavior is acceptable
  1703. */
  1704. public get zOrder(): number {
  1705. return this._manualZOrder;
  1706. }
  1707. public set zOrder(value: number) {
  1708. if (this._manualZOrder === value) {
  1709. return;
  1710. }
  1711. this._manualZOrder = value;
  1712. this.onZOrderChanged();
  1713. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  1714. this._actualZOrderChangedObservable.notifyObservers(value);
  1715. }
  1716. }
  1717. public get isManualZOrder(): boolean {
  1718. return this._manualZOrder != null;
  1719. }
  1720. @dynamicLevelProperty(10, pi => Prim2DBase.marginProperty = pi)
  1721. /**
  1722. * You can get/set a margin on the primitive through this property
  1723. * @returns the margin object, if there was none, a default one is created and returned
  1724. */
  1725. public get margin(): PrimitiveThickness {
  1726. if (!this._margin) {
  1727. this._margin = new PrimitiveThickness(() => {
  1728. if (!this.parent) {
  1729. return null;
  1730. }
  1731. return this.parent.margin;
  1732. }, () => this._positioningDirty());
  1733. }
  1734. return this._margin;
  1735. }
  1736. private get _hasMargin(): boolean {
  1737. return (this._margin !== null) || (this._marginAlignment !== null);
  1738. }
  1739. @dynamicLevelProperty(11, pi => Prim2DBase.paddingProperty = pi)
  1740. /**
  1741. * You can get/set a margin on the primitive through this property
  1742. * @returns the margin object, if there was none, a default one is created and returned
  1743. */
  1744. public get padding(): PrimitiveThickness {
  1745. if (!this._padding) {
  1746. this._padding = new PrimitiveThickness(() => {
  1747. if (!this.parent) {
  1748. return null;
  1749. }
  1750. return this.parent.padding;
  1751. }, () => this._positioningDirty());
  1752. }
  1753. return this._padding;
  1754. }
  1755. private get _hasPadding(): boolean {
  1756. return this._padding !== null;
  1757. }
  1758. @dynamicLevelProperty(12, pi => Prim2DBase.marginAlignmentProperty = pi)
  1759. /**
  1760. * You can get/set the margin alignment through this property
  1761. */
  1762. public get marginAlignment(): PrimitiveAlignment {
  1763. if (!this._marginAlignment) {
  1764. this._marginAlignment = new PrimitiveAlignment(() => this._positioningDirty());
  1765. }
  1766. return this._marginAlignment;
  1767. }
  1768. @instanceLevelProperty(13, pi => Prim2DBase.opacityProperty = pi)
  1769. /**
  1770. * Get/set the opacity of the whole primitive
  1771. */
  1772. public get opacity(): number {
  1773. return this._opacity;
  1774. }
  1775. public set opacity(value: number) {
  1776. if (value < 0) {
  1777. value = 0;
  1778. } else if (value > 1) {
  1779. value = 1;
  1780. }
  1781. if (this._opacity === value) {
  1782. return;
  1783. }
  1784. this._opacity = value;
  1785. this._updateRenderMode();
  1786. this._setFlags(SmartPropertyPrim.flagActualOpacityDirty);
  1787. this._spreadActualOpacityChanged();
  1788. }
  1789. @instanceLevelProperty(14, pi => Prim2DBase.scaleXProperty = pi, false, true)
  1790. /**
  1791. * Scale applied on the X axis of the primitive
  1792. */
  1793. public set scaleX(value: number) {
  1794. this._scale.x = value;
  1795. }
  1796. public get scaleX(): number {
  1797. return this._scale.x;
  1798. }
  1799. @instanceLevelProperty(15, pi => Prim2DBase.scaleYProperty = pi, false, true)
  1800. /**
  1801. * Scale applied on the Y axis of the primitive
  1802. */
  1803. public set scaleY(value: number) {
  1804. this._scale.y = value;
  1805. }
  1806. public get scaleY(): number {
  1807. return this._scale.y;
  1808. }
  1809. public get actualOpacity(): number {
  1810. if (this._isFlagSet(SmartPropertyPrim.flagActualOpacityDirty)) {
  1811. let cur = this.parent;
  1812. let op = this.opacity;
  1813. while (cur) {
  1814. op *= cur.opacity;
  1815. cur = cur.parent;
  1816. }
  1817. this._actualOpacity = op;
  1818. this._clearFlags(SmartPropertyPrim.flagActualOpacityDirty);
  1819. }
  1820. return this._actualOpacity;
  1821. }
  1822. /**
  1823. * Get/set the layout engine to use for this primitive.
  1824. * The default layout engine is the CanvasLayoutEngine.
  1825. */
  1826. public get layoutEngine(): LayoutEngineBase {
  1827. if (!this._layoutEngine) {
  1828. this._layoutEngine = CanvasLayoutEngine.Singleton;
  1829. }
  1830. return this._layoutEngine;
  1831. }
  1832. public set layoutEngine(value: LayoutEngineBase) {
  1833. if (this._layoutEngine === value) {
  1834. return;
  1835. }
  1836. this._changeLayoutEngine(value);
  1837. }
  1838. /**
  1839. * Get/set the layout are of this primitive.
  1840. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  1841. * The setter should only be called by a Layout Engine class.
  1842. */
  1843. public get layoutArea(): Size {
  1844. return this._layoutArea;
  1845. }
  1846. public set layoutArea(val: Size) {
  1847. if (this._layoutArea.equals(val)) {
  1848. return;
  1849. }
  1850. this._positioningDirty();
  1851. this._layoutArea = val;
  1852. }
  1853. /**
  1854. * Get/set the layout area position (relative to the parent primitive).
  1855. * The setter should only be called by a Layout Engine class.
  1856. */
  1857. public get layoutAreaPos(): Vector2 {
  1858. return this._layoutAreaPos;
  1859. }
  1860. public set layoutAreaPos(val: Vector2) {
  1861. if (this._layoutAreaPos.equals(val)) {
  1862. return;
  1863. }
  1864. this._positioningDirty();
  1865. this._layoutAreaPos = val;
  1866. }
  1867. /**
  1868. * Define if the Primitive can be subject to intersection test or not (default is true)
  1869. */
  1870. public get isPickable(): boolean {
  1871. return this._isFlagSet(SmartPropertyPrim.flagIsPickable);
  1872. }
  1873. public set isPickable(value: boolean) {
  1874. this._changeFlags(SmartPropertyPrim.flagIsPickable, value);
  1875. }
  1876. /**
  1877. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  1878. */
  1879. public get hierarchyDepth(): number {
  1880. return this._hierarchyDepth;
  1881. }
  1882. /**
  1883. * Retrieve the Group that is responsible to render this primitive
  1884. */
  1885. public get renderGroup(): Group2D {
  1886. return this._renderGroup;
  1887. }
  1888. /**
  1889. * Get the global transformation matrix of the primitive
  1890. */
  1891. public get globalTransform(): Matrix {
  1892. return this._globalTransform;
  1893. }
  1894. /**
  1895. * return the global position of the primitive, relative to its canvas
  1896. */
  1897. public getGlobalPosition(): Vector2 {
  1898. let v = new Vector2(0, 0);
  1899. this.getGlobalPositionByRef(v);
  1900. return v;
  1901. }
  1902. /**
  1903. * return the global position of the primitive, relative to its canvas
  1904. * @param v the valid Vector2 object where the global position will be stored
  1905. */
  1906. public getGlobalPositionByRef(v: Vector2) {
  1907. v.x = this.globalTransform.m[12];
  1908. v.y = this.globalTransform.m[13];
  1909. }
  1910. /**
  1911. * Get invert of the global transformation matrix of the primitive
  1912. */
  1913. public get invGlobalTransform(): Matrix {
  1914. return this._invGlobalTransform;
  1915. }
  1916. /**
  1917. * Get the local transformation of the primitive
  1918. */
  1919. public get localTransform(): Matrix {
  1920. this._updateLocalTransform();
  1921. return this._localTransform;
  1922. }
  1923. private static _bMax = Vector2.Zero();
  1924. /**
  1925. * Get the boundingInfo associated to the primitive and its children.
  1926. * The value is supposed to be always up to date
  1927. */
  1928. public get boundingInfo(): BoundingInfo2D {
  1929. if (this._isFlagSet(SmartPropertyPrim.flagBoundingInfoDirty)) {
  1930. if (this.owner) {
  1931. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  1932. }
  1933. if (this.isSizedByContent) {
  1934. this._boundingInfo.clear();
  1935. } else {
  1936. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  1937. }
  1938. let bi = this._boundingInfo;
  1939. var tps = new BoundingInfo2D();
  1940. for (let curChild of this._children) {
  1941. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  1942. bi.unionToRef(tps, bi);
  1943. }
  1944. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  1945. this._boundingSize.copyFromFloats(
  1946. (!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width,
  1947. (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  1948. this._clearFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  1949. }
  1950. return this._boundingInfo;
  1951. }
  1952. /**
  1953. * Determine if the size is automatically computed or fixed because manually specified.
  1954. * Use the actualSize property to get the final/real size of the primitive
  1955. * @returns true if the size is automatically computed, false if it were manually specified.
  1956. */
  1957. public get isSizeAuto(): boolean {
  1958. return this._size == null;
  1959. }
  1960. /**
  1961. * Return true if this prim has an auto size which is set by the children's global bounding box
  1962. */
  1963. public get isSizedByContent(): boolean {
  1964. return (this._size == null) && (this._children.length > 0);
  1965. }
  1966. /**
  1967. * Determine if the position is automatically computed or fixed because manually specified.
  1968. * Use the actualPosition property to get the final/real position of the primitive
  1969. * @returns true if the position is automatically computed, false if it were manually specified.
  1970. */
  1971. public get isPositionAuto(): boolean {
  1972. return this._position == null;
  1973. }
  1974. /**
  1975. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  1976. */
  1977. public get pointerEventObservable(): Observable<PrimitivePointerInfo> {
  1978. return this._pointerEventObservable;
  1979. }
  1980. public get zActualOrderChangedObservable(): Observable<number> {
  1981. if (!this._actualZOrderChangedObservable) {
  1982. this._actualZOrderChangedObservable = new Observable<number>();
  1983. }
  1984. return this._actualZOrderChangedObservable;
  1985. }
  1986. public findById(id: string): Prim2DBase {
  1987. if (this._id === id) {
  1988. return this;
  1989. }
  1990. for (let child of this._children) {
  1991. let r = child.findById(id);
  1992. if (r != null) {
  1993. return r;
  1994. }
  1995. }
  1996. }
  1997. protected onZOrderChanged() {
  1998. }
  1999. protected levelIntersect(intersectInfo: IntersectInfo2D): boolean {
  2000. return false;
  2001. }
  2002. /**
  2003. * Capture all the Events of the given PointerId for this primitive.
  2004. * Don't forget to call releasePointerEventsCapture when done.
  2005. * @param pointerId the Id of the pointer to capture the events from.
  2006. */
  2007. public setPointerEventCapture(pointerId: number): boolean {
  2008. return this.owner._setPointerCapture(pointerId, this);
  2009. }
  2010. /**
  2011. * Release a captured pointer made with setPointerEventCapture.
  2012. * @param pointerId the Id of the pointer to release the capture from.
  2013. */
  2014. public releasePointerEventsCapture(pointerId: number): boolean {
  2015. return this.owner._releasePointerCapture(pointerId, this);
  2016. }
  2017. /**
  2018. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  2019. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  2020. */
  2021. public intersect(intersectInfo: IntersectInfo2D): boolean {
  2022. if (!intersectInfo) {
  2023. return false;
  2024. }
  2025. // If this is null it means this method is call for the first level, initialize stuffs
  2026. let firstLevel = !intersectInfo._globalPickPosition;
  2027. if (firstLevel) {
  2028. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  2029. intersectInfo._globalPickPosition = Vector2.Zero();
  2030. Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  2031. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  2032. intersectInfo.intersectedPrimitives = new Array<PrimitiveIntersectedInfo>();
  2033. intersectInfo.topMostIntersectedPrimitive = null;
  2034. }
  2035. if (!intersectInfo.intersectHidden && !this.isVisible) {
  2036. return false;
  2037. }
  2038. // Fast rejection test with boundingInfo
  2039. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  2040. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  2041. intersectInfo._exit(firstLevel);
  2042. return false;
  2043. }
  2044. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  2045. let levelIntersectRes = false;
  2046. if (this.isPickable) {
  2047. levelIntersectRes = this.levelIntersect(intersectInfo);
  2048. if (levelIntersectRes) {
  2049. let pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  2050. intersectInfo.intersectedPrimitives.push(pii);
  2051. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  2052. intersectInfo.topMostIntersectedPrimitive = pii;
  2053. }
  2054. // If we must stop at the first intersection, we're done, quit!
  2055. if (intersectInfo.findFirstOnly) {
  2056. intersectInfo._exit(firstLevel);
  2057. return true;
  2058. }
  2059. }
  2060. }
  2061. // Recurse to children if needed
  2062. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  2063. for (let curChild of this._children) {
  2064. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  2065. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  2066. continue;
  2067. }
  2068. // Must compute the localPickLocation for the children level
  2069. Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  2070. // If we got an intersection with the child and we only need to find the first one, quit!
  2071. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  2072. intersectInfo._exit(firstLevel);
  2073. return true;
  2074. }
  2075. }
  2076. }
  2077. intersectInfo._exit(firstLevel);
  2078. return intersectInfo.isIntersected;
  2079. }
  2080. public moveChild(child: Prim2DBase, previous: Prim2DBase): boolean {
  2081. if (child.parent !== this) {
  2082. return false;
  2083. }
  2084. let childIndex = this._children.indexOf(child);
  2085. let prevIndex = previous ? this._children.indexOf(previous) : -1;
  2086. if (!this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder)) {
  2087. this._setFlags(SmartPropertyPrim.flagZOrderDirty);
  2088. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex+1);
  2089. }
  2090. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  2091. }
  2092. private addChild(child: Prim2DBase) {
  2093. child._parent = this;
  2094. this._boundingBoxDirty();
  2095. let flat = this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder);
  2096. if (flat) {
  2097. child._setFlags(SmartPropertyPrim.flagChildrenFlatZOrder);
  2098. child._setZOrder(this._zOrder, true);
  2099. child._zMax = this._zOrder;
  2100. } else {
  2101. this._setFlags(SmartPropertyPrim.flagZOrderDirty);
  2102. }
  2103. let length = this._children.push(child);
  2104. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  2105. }
  2106. /**
  2107. * Dispose the primitive, remove it from its parent.
  2108. */
  2109. public dispose(): boolean {
  2110. if (!super.dispose()) {
  2111. return false;
  2112. }
  2113. if (this._actionManager) {
  2114. this._actionManager.dispose();
  2115. this._actionManager = null;
  2116. }
  2117. // If there's a parent, remove this object from its parent list
  2118. if (this._parent) {
  2119. let i = this._parent._children.indexOf(this);
  2120. if (i !== undefined) {
  2121. this._parent._children.splice(i, 1);
  2122. }
  2123. this._parent = null;
  2124. }
  2125. // Recurse dispose to children
  2126. if (this._children) {
  2127. while (this._children.length > 0) {
  2128. this._children[this._children.length - 1].dispose();
  2129. }
  2130. }
  2131. return true;
  2132. }
  2133. protected onPrimBecomesDirty() {
  2134. if (this._renderGroup && !this._isFlagSet(SmartPropertyPrim.flagPrimInDirtyList)) {
  2135. this._renderGroup._addPrimToDirtyList(this);
  2136. this._setFlags(SmartPropertyPrim.flagPrimInDirtyList);
  2137. }
  2138. }
  2139. public _needPrepare(): boolean {
  2140. return this._areSomeFlagsSet(SmartPropertyPrim.flagVisibilityChanged | SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  2141. }
  2142. public _prepareRender(context: PrepareRender2DContext) {
  2143. this._prepareRenderPre(context);
  2144. this._prepareRenderPost(context);
  2145. }
  2146. public _prepareRenderPre(context: PrepareRender2DContext) {
  2147. }
  2148. public _prepareRenderPost(context: PrepareRender2DContext) {
  2149. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  2150. if (this instanceof Group2D) {
  2151. var self: any = this;
  2152. if (self.isRenderableGroup) {
  2153. return;
  2154. }
  2155. }
  2156. // Check if we need to recurse the prepare to children primitives
  2157. // - must have children
  2158. // - the global transform of this level have changed, or
  2159. // - the visible state of primitive has changed
  2160. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  2161. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  2162. this._children.forEach(c => {
  2163. // As usual stop the recursion if we meet a renderable group
  2164. if (!(c instanceof Group2D && c.isRenderableGroup)) {
  2165. c._prepareRender(context);
  2166. }
  2167. });
  2168. }
  2169. // Finally reset the dirty flags as we've processed everything
  2170. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  2171. this._instanceDirtyFlags = 0;
  2172. }
  2173. protected _canvasPreInit(settings: any) {
  2174. }
  2175. protected static _isCanvasInit: boolean = false;
  2176. protected static CheckParent(parent: Prim2DBase) { // TODO remove
  2177. //if (!Prim2DBase._isCanvasInit && !parent) {
  2178. // throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  2179. //}
  2180. }
  2181. protected updateCachedStatesOf(list: Prim2DBase[], recurse: boolean) {
  2182. for (let cur of list) {
  2183. cur.updateCachedStates(recurse);
  2184. }
  2185. }
  2186. private _parentLayoutDirty() {
  2187. if (!this._parent || this._parent.isDisposed) {
  2188. return;
  2189. }
  2190. this._parent._setLayoutDirty();
  2191. }
  2192. protected _setLayoutDirty() {
  2193. this.onPrimBecomesDirty();
  2194. this._setFlags(SmartPropertyPrim.flagLayoutDirty);
  2195. }
  2196. private _checkPositionChange(): boolean {
  2197. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  2198. console.log(`Can't manually set the position of ${this.id}, the Layout Engine of its parent doesn't allow it`);
  2199. return false;
  2200. }
  2201. return true;
  2202. }
  2203. protected _positioningDirty() {
  2204. this.onPrimBecomesDirty();
  2205. this._setFlags(SmartPropertyPrim.flagPositioningDirty);
  2206. }
  2207. protected _spreadActualOpacityChanged() {
  2208. for (let child of this._children) {
  2209. child._setFlags(SmartPropertyPrim.flagActualOpacityDirty);
  2210. child._spreadActualOpacityChanged();
  2211. }
  2212. }
  2213. private _changeLayoutEngine(engine: LayoutEngineBase) {
  2214. this._layoutEngine = engine;
  2215. }
  2216. private static _t0: Matrix = new Matrix();
  2217. private static _t1: Matrix = new Matrix();
  2218. private static _t2: Matrix = new Matrix();
  2219. private static _v0: Vector2 = Vector2.Zero(); // Must stay with the value 0,0
  2220. private _updateLocalTransform(): boolean {
  2221. let tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  2222. if (this.checkPropertiesDirty(tflags)) {
  2223. if (this.owner) {
  2224. this.owner.addupdateLocalTransformCounter(1);
  2225. }
  2226. var rot = Quaternion.RotationAxis(new Vector3(0, 0, 1), this._rotation);
  2227. var local: Matrix;
  2228. let pos = this.position;
  2229. if (this._origin.x === 0 && this._origin.y === 0) {
  2230. local = Matrix.Compose(new Vector3(this._scale.x, this._scale.y, 1), rot, new Vector3(pos.x, pos.y, 0));
  2231. this._localTransform = local;
  2232. } else {
  2233. // -Origin offset
  2234. let as = this.actualSize;
  2235. Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  2236. // -Origin * rotation
  2237. rot.toRotationMatrix(Prim2DBase._t1);
  2238. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  2239. // -Origin * rotation * scale
  2240. Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  2241. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  2242. // -Origin * rotation * scale * (Origin + Position)
  2243. Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  2244. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  2245. }
  2246. this.clearPropertiesDirty(tflags);
  2247. return true;
  2248. }
  2249. return false;
  2250. }
  2251. private static _transMtx = Matrix.Zero();
  2252. protected updateCachedStates(recurse: boolean) {
  2253. if (this.isDisposed) {
  2254. return;
  2255. }
  2256. this.owner.addCachedGroupRenderCounter(1);
  2257. // Check if the parent is synced
  2258. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(SmartPropertyPrim.flagLayoutDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagZOrderDirty))) {
  2259. this._parent.updateCachedStates(false);
  2260. }
  2261. // Update Z-Order if needed
  2262. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  2263. this._updateZOrder();
  2264. }
  2265. // Update actualSize only if there' not positioning to recompute and the size changed
  2266. // Otherwise positioning will take care of it.
  2267. let sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  2268. if (!this._isFlagSet(SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  2269. let size = this.size;
  2270. if (size) {
  2271. if (this.size.width != null) {
  2272. this.actualSize.width = this.size.width;
  2273. }
  2274. if (this.size.height != null) {
  2275. this.actualSize.height = this.size.height;
  2276. }
  2277. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  2278. }
  2279. }
  2280. // Check for layout update
  2281. let positioningDirty = this._isFlagSet(SmartPropertyPrim.flagPositioningDirty);
  2282. if (this._isFlagSet(SmartPropertyPrim.flagLayoutDirty)) {
  2283. this.owner.addUpdateLayoutCounter(1);
  2284. this._layoutEngine.updateLayout(this);
  2285. this._clearFlags(SmartPropertyPrim.flagLayoutDirty);
  2286. }
  2287. let positioningComputed = positioningDirty && !this._isFlagSet(SmartPropertyPrim.flagPositioningDirty);
  2288. let autoContentChanged = false;
  2289. if (this.isSizeAuto) {
  2290. if (!this._lastAutoSizeArea) {
  2291. autoContentChanged = this.size!==null;
  2292. } else {
  2293. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  2294. }
  2295. }
  2296. // Check for positioning update
  2297. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  2298. this._updatePositioning();
  2299. this._clearFlags(SmartPropertyPrim.flagPositioningDirty);
  2300. if (sizeDirty) {
  2301. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  2302. }
  2303. positioningComputed = true;
  2304. }
  2305. if (positioningComputed && this._parent) {
  2306. this._parentContentArea.copyFrom(this._parent.contentArea);
  2307. }
  2308. // Check if we must update this prim
  2309. if (this === <any>this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  2310. this.owner.addUpdateGlobalTransformCounter(1);
  2311. let curVisibleState = this.isVisible;
  2312. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  2313. // Detect a change of visibility
  2314. this._changeFlags(SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  2315. // Get/compute the localTransform
  2316. let localDirty = this._updateLocalTransform();
  2317. let parentPaddingChanged = false;
  2318. let parentPaddingOffset: Vector2 = Prim2DBase._v0;
  2319. if (this._parent) {
  2320. parentPaddingOffset = this._parent._paddingOffset;
  2321. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  2322. }
  2323. // Check if there are changes in the parent that will force us to update the global matrix
  2324. let parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  2325. // Check if we have to update the globalTransform
  2326. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  2327. let globalTransform = this._parent ? this._parent._globalTransform : null;
  2328. let localTransform: Matrix;
  2329. Prim2DBase._transMtx.copyFrom(this._localTransform);
  2330. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  2331. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  2332. localTransform = Prim2DBase._transMtx;
  2333. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  2334. this._invGlobalTransform = Matrix.Invert(this._globalTransform);
  2335. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  2336. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  2337. }
  2338. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  2339. }
  2340. if (recurse) {
  2341. for (let child of this._children) {
  2342. // Stop the recursion if we meet a renderable group
  2343. child.updateCachedStates(!(child instanceof Group2D && child.isRenderableGroup));
  2344. }
  2345. }
  2346. }
  2347. private static _icPos = Vector2.Zero();
  2348. private static _icArea = Size.Zero();
  2349. private static _size = Size.Zero();
  2350. private _updatePositioning() {
  2351. if (this.owner) {
  2352. this.owner.addUpdatePositioningCounter(1);
  2353. }
  2354. // From this point we assume that the primitive layoutArea is computed and up to date.
  2355. // We know have to :
  2356. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  2357. // 2. Determine the contentArea based on the padding property.
  2358. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  2359. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  2360. if (this.actualSize.width == null) {
  2361. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  2362. }
  2363. if (this.actualSize.height == null) {
  2364. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  2365. }
  2366. }
  2367. // Apply margin
  2368. if (this._hasMargin) {
  2369. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  2370. this.actualSize = Prim2DBase._size.clone();
  2371. }
  2372. let isSizeAuto = this.isSizeAuto;
  2373. if (this._hasPadding) {
  2374. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  2375. if (isSizeAuto) {
  2376. let content = this.size.clone();
  2377. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  2378. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  2379. this._contentArea.copyFrom(content);
  2380. this.actualSize = Prim2DBase._size.clone();
  2381. // Changing the padding has resize the prim, which forces us to recompute margin again
  2382. if (this._hasMargin) {
  2383. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  2384. }
  2385. } else {
  2386. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  2387. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  2388. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  2389. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  2390. this._paddingOffset.x += Prim2DBase._icPos.x;
  2391. this._paddingOffset.y += Prim2DBase._icPos.y;
  2392. this._contentArea.copyFrom(Prim2DBase._size);
  2393. }
  2394. } else {
  2395. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  2396. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  2397. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  2398. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  2399. this._contentArea.copyFrom(Prim2DBase._icArea);
  2400. }
  2401. if (!this._position) {
  2402. let aPos = new Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  2403. this.actualPosition = aPos;
  2404. }
  2405. if (isSizeAuto) {
  2406. this._lastAutoSizeArea = this.size;
  2407. }
  2408. }
  2409. /**
  2410. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  2411. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  2412. */
  2413. public get contentArea(): Size {
  2414. // Check for positioning update
  2415. if (this._isFlagSet(SmartPropertyPrim.flagPositioningDirty)) {
  2416. this._updatePositioning();
  2417. this._clearFlags(SmartPropertyPrim.flagPositioningDirty);
  2418. }
  2419. return this._contentArea;
  2420. }
  2421. public _patchHierarchy(owner: Canvas2D) {
  2422. this._owner = owner;
  2423. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  2424. if (this._renderGroup != null) {
  2425. return;
  2426. }
  2427. if (this instanceof Group2D) {
  2428. var group: any = this;
  2429. group.detectGroupStates();
  2430. if (group._trackedNode && !group._isFlagSet(SmartPropertyPrim.flagTrackedGroup)) {
  2431. group.owner._registerTrackedNode(this);
  2432. }
  2433. }
  2434. this._renderGroup = <Group2D>this.traverseUp(p => p instanceof Group2D && p.isRenderableGroup);
  2435. if (this._parent) {
  2436. this._parentLayoutDirty();
  2437. }
  2438. // Make sure the prim is in the dirtyList if it should be
  2439. if (this._renderGroup && this.isDirty) {
  2440. let list = this._renderGroup._renderableData._primDirtyList;
  2441. let i = list.indexOf(this);
  2442. if (i === -1) {
  2443. list.push(this);
  2444. }
  2445. }
  2446. // Recurse
  2447. for (let child of this._children) {
  2448. child._hierarchyDepth = this._hierarchyDepth + 1;
  2449. child._patchHierarchy(owner);
  2450. }
  2451. }
  2452. private static _zOrderChangedNotifList = new Array<Prim2DBase>();
  2453. private static _zRebuildReentrency = false;
  2454. private _updateZOrder() {
  2455. let prevLinPos = this._primLinearPosition;
  2456. let startI = 0;
  2457. let startZ = this._zOrder;
  2458. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  2459. let childrenCount = this._children.length;
  2460. if (this._firstZDirtyIndex > 0) {
  2461. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  2462. let prevPrim = this._children[this._firstZDirtyIndex - 1];
  2463. prevLinPos = prevPrim._primLinearPosition;
  2464. startI = this._firstZDirtyIndex - 1;
  2465. startZ = prevPrim._zOrder;
  2466. }
  2467. }
  2468. let startPos = prevLinPos;
  2469. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  2470. Prim2DBase._totalCount = 0;
  2471. for (let i = startI; i < childrenCount; i++) {
  2472. let child = this._children[i];
  2473. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  2474. }
  2475. // Compute the new Z-Order for all the primitives
  2476. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  2477. let zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  2478. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  2479. if (zDelta < Canvas2D._zMinDelta) {
  2480. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  2481. if (Prim2DBase._zRebuildReentrency) {
  2482. let p = this._parent;
  2483. if (p == null) {
  2484. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  2485. console.log(`Can't compute Z-Order for ${this.id}'s children, zDelta is too small, Z-Order is now in an unstable state`);
  2486. Prim2DBase._zRebuildReentrency = false;
  2487. return;
  2488. }
  2489. p._firstZDirtyIndex = 0;
  2490. return p._updateZOrder();
  2491. }
  2492. Prim2DBase._zRebuildReentrency = true;
  2493. this._firstZDirtyIndex = 0;
  2494. this._updateZOrder();
  2495. Prim2DBase._zRebuildReentrency = false;
  2496. }
  2497. for (let i = startI; i < childrenCount; i++) {
  2498. let child = this._children[i];
  2499. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  2500. }
  2501. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  2502. for (let p of Prim2DBase._zOrderChangedNotifList) {
  2503. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  2504. }
  2505. Prim2DBase._zOrderChangedNotifList.splice(0);
  2506. this._firstZDirtyIndex = Prim2DBase._bigInt;
  2507. this._clearFlags(SmartPropertyPrim.flagZOrderDirty);
  2508. }
  2509. private static _totalCount: number = 0;
  2510. private _updatePrimitiveLinearPosition(prevLinPos: number): number {
  2511. if (this.isManualZOrder) {
  2512. return prevLinPos;
  2513. }
  2514. this._primLinearPosition = ++prevLinPos;
  2515. Prim2DBase._totalCount++;
  2516. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  2517. if (!this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder)) {
  2518. for (let child of this._children) {
  2519. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  2520. }
  2521. }
  2522. return prevLinPos;
  2523. }
  2524. private _updatePrimitiveZOrder(startPos: number, startZ: number, deltaZ: number): number {
  2525. if (this.isManualZOrder) {
  2526. return null;
  2527. }
  2528. let newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  2529. let isFlat = this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder);
  2530. this._setZOrder(newZ, false);
  2531. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  2532. this._firstZDirtyIndex = Prim2DBase._bigInt;
  2533. this._clearFlags(SmartPropertyPrim.flagZOrderDirty);
  2534. }
  2535. let curZ: number = newZ;
  2536. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  2537. if (isFlat) {
  2538. if (this._children.length > 0) {
  2539. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  2540. for (let child of this._children) {
  2541. child._updatePrimitiveFlatZOrder(this._zOrder);
  2542. }
  2543. }
  2544. } else {
  2545. for (let child of this._children) {
  2546. let r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  2547. if (r != null) {
  2548. curZ = r;
  2549. }
  2550. }
  2551. }
  2552. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  2553. return curZ;
  2554. }
  2555. private _updatePrimitiveFlatZOrder(newZ: number) {
  2556. if (this.isManualZOrder) {
  2557. return;
  2558. }
  2559. this._setZOrder(newZ, false);
  2560. this._zMax = newZ;
  2561. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  2562. this._firstZDirtyIndex = Prim2DBase._bigInt;
  2563. this._clearFlags(SmartPropertyPrim.flagZOrderDirty);
  2564. }
  2565. for (let child of this._children) {
  2566. child._updatePrimitiveFlatZOrder(newZ);
  2567. }
  2568. }
  2569. private _setZOrder(newZ: number, directEmit: boolean) {
  2570. if (newZ !== this._zOrder) {
  2571. this._zOrder = newZ;
  2572. this.onPrimBecomesDirty();
  2573. this.onZOrderChanged();
  2574. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  2575. if (directEmit) {
  2576. this._actualZOrderChangedObservable.notifyObservers(newZ);
  2577. } else {
  2578. Prim2DBase._zOrderChangedNotifList.push(this);
  2579. }
  2580. }
  2581. }
  2582. }
  2583. protected _updateRenderMode() {
  2584. }
  2585. /**
  2586. * This method is used to alter the contentArea of the Primitive before margin is applied.
  2587. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  2588. * @param primSize the current size of the primitive
  2589. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  2590. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  2591. */
  2592. protected _getInitialContentAreaToRef(primSize: Size, initialContentPosition: Vector2, initialContentArea: Size) {
  2593. initialContentArea.copyFrom(primSize);
  2594. initialContentPosition.x = initialContentPosition.y = 0;
  2595. }
  2596. /**
  2597. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  2598. * Check the Rectangle2D implementation for a concrete application.
  2599. * @param primSize the current size of the primitive
  2600. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  2601. */
  2602. protected _getActualSizeFromContentToRef(primSize: Size, newPrimSize: Size) {
  2603. newPrimSize.copyFrom(primSize);
  2604. }
  2605. private _owner: Canvas2D;
  2606. private _parent: Prim2DBase;
  2607. private _actionManager: ActionManager;
  2608. protected _children: Array<Prim2DBase>;
  2609. private _renderGroup: Group2D;
  2610. protected _hierarchyDepth: number;
  2611. protected _zOrder: number;
  2612. private _manualZOrder: number;
  2613. protected _zMax: number;
  2614. private _firstZDirtyIndex: number;
  2615. private _primLinearPosition: number;
  2616. private _margin: PrimitiveThickness;
  2617. private _padding: PrimitiveThickness;
  2618. private _marginAlignment: PrimitiveAlignment;
  2619. public _pointerEventObservable: Observable<PrimitivePointerInfo>;
  2620. private _actualZOrderChangedObservable: Observable<number>;
  2621. private _id: string;
  2622. private _position: Vector2;
  2623. private _actualPosition: Vector2;
  2624. protected _size: Size;
  2625. protected _actualSize: Size;
  2626. public _boundingSize: Size;
  2627. protected _minSize: Size;
  2628. protected _maxSize: Size;
  2629. protected _desiredSize: Size;
  2630. private _layoutEngine: LayoutEngineBase;
  2631. private _marginOffset: Vector2;
  2632. private _paddingOffset: Vector2;
  2633. private _parentPaddingOffset: Vector2;
  2634. private _parentContentArea: Size;
  2635. private _lastAutoSizeArea: Size;
  2636. private _layoutAreaPos: Vector2;
  2637. private _layoutArea: Size;
  2638. private _contentArea: Size;
  2639. private _rotation: number;
  2640. private _scale: Vector2;
  2641. private _origin: Vector2;
  2642. protected _opacity: number;
  2643. private _actualOpacity: number;
  2644. // Stores the step of the parent for which the current global transform was computed
  2645. // If the parent has a new step, it means this prim's global transform must be updated
  2646. protected _parentTransformStep: number;
  2647. // Stores the step corresponding of the global transform for this prim
  2648. // If a child prim has an older _parentTransformStep it means the child's transform should be updated
  2649. protected _globalTransformStep: number;
  2650. // Stores the previous
  2651. protected _globalTransformProcessStep: number;
  2652. protected _localTransform: Matrix;
  2653. protected _globalTransform: Matrix;
  2654. protected _invGlobalTransform: Matrix;
  2655. }
  2656. }