babylon.prim2dBase.ts 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498
  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. @className("PrimitiveAlignment", "BABYLON")
  262. export class PrimitiveAlignment {
  263. constructor(changeCallback?: () => void) {
  264. this._changedCallback = changeCallback;
  265. this._horizontal = PrimitiveAlignment.AlignLeft;
  266. this._vertical = PrimitiveAlignment.AlignBottom;
  267. }
  268. /**
  269. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  270. */
  271. public static get AlignLeft(): number { return PrimitiveAlignment._AlignLeft; }
  272. /**
  273. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  274. */
  275. public static get AlignTop(): number { return PrimitiveAlignment._AlignTop; }
  276. /**
  277. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  278. */
  279. public static get AlignRight(): number { return PrimitiveAlignment._AlignRight; }
  280. /**
  281. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  282. */
  283. public static get AlignBottom(): number { return PrimitiveAlignment._AlignBottom; }
  284. /**
  285. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  286. */
  287. public static get AlignCenter(): number { return PrimitiveAlignment._AlignCenter; }
  288. /**
  289. * The content is stretched toward the opposite edges of the Primitive
  290. */
  291. public static get AlignStretch(): number { return PrimitiveAlignment._AlignStretch; }
  292. private static _AlignLeft = 1;
  293. private static _AlignTop = 1; // Same as left
  294. private static _AlignRight = 2;
  295. private static _AlignBottom = 2; // Same as right
  296. private static _AlignCenter = 3;
  297. private static _AlignStretch = 4;
  298. /**
  299. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  300. */
  301. public get horizontal(): number {
  302. return this._horizontal;
  303. }
  304. public set horizontal(value: number) {
  305. if (this._horizontal === value) {
  306. return;
  307. }
  308. this._horizontal = value;
  309. this.onChangeCallback();
  310. }
  311. /**
  312. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  313. */
  314. public get vertical(): number {
  315. return this._vertical;
  316. }
  317. public set vertical(value: number) {
  318. if (this._vertical === value) {
  319. return;
  320. }
  321. this._vertical = value;
  322. this.onChangeCallback();
  323. }
  324. private onChangeCallback() {
  325. if (this._changedCallback) {
  326. this._changedCallback();
  327. }
  328. }
  329. private _changedCallback: () => void;
  330. private _horizontal: number;
  331. private _vertical: number;
  332. /**
  333. * Set the horizontal alignment from a string value.
  334. * @param text can be either: 'left','right','center','stretch'
  335. */
  336. setHorizontal(text: string) {
  337. let v = text.trim().toLocaleLowerCase();
  338. switch (v) {
  339. case "left":
  340. this.horizontal = PrimitiveAlignment.AlignLeft;
  341. return;
  342. case "right":
  343. this.horizontal = PrimitiveAlignment.AlignRight;
  344. return;
  345. case "center":
  346. this.horizontal = PrimitiveAlignment.AlignCenter;
  347. return;
  348. case "stretch":
  349. this.horizontal = PrimitiveAlignment.AlignStretch;
  350. return;
  351. }
  352. }
  353. /**
  354. * Set the vertical alignment from a string value.
  355. * @param text can be either: 'top','bottom','center','stretch'
  356. */
  357. setVertical(text: string) {
  358. let v = text.trim().toLocaleLowerCase();
  359. switch (v) {
  360. case "top":
  361. this.vertical = PrimitiveAlignment.AlignTop;
  362. return;
  363. case "bottom":
  364. this.vertical = PrimitiveAlignment.AlignBottom;
  365. return;
  366. case "center":
  367. this.vertical = PrimitiveAlignment.AlignCenter;
  368. return;
  369. case "stretch":
  370. this.vertical = PrimitiveAlignment.AlignStretch;
  371. return;
  372. }
  373. }
  374. /**
  375. * Set the horizontal and or vertical alignments from a string value.
  376. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  377. */
  378. fromString(value: string) {
  379. let m = value.trim().split(",");
  380. if (m.length === 1) {
  381. this.setHorizontal(m[0]);
  382. this.setVertical(m[0]);
  383. } else {
  384. for (let v of m) {
  385. v = v.toLocaleLowerCase().trim();
  386. // Horizontal
  387. let i = v.indexOf("h:");
  388. if (i === -1) {
  389. i = v.indexOf("horizontal:");
  390. }
  391. if (i !== -1) {
  392. v = v.substr(v.indexOf(":") + 1);
  393. this.setHorizontal(v);
  394. continue;
  395. }
  396. // Vertical
  397. i = v.indexOf("v:");
  398. if (i === -1) {
  399. i = v.indexOf("vertical:");
  400. }
  401. if (i !== -1) {
  402. v = v.substr(v.indexOf(":") + 1);
  403. this.setVertical(v);
  404. continue;
  405. }
  406. }
  407. }
  408. }
  409. copyFrom(pa: PrimitiveAlignment) {
  410. this._horizontal = pa._horizontal;
  411. this._vertical = pa._vertical;
  412. this.onChangeCallback();
  413. }
  414. public get isDefault(): boolean {
  415. return this.horizontal === PrimitiveAlignment.AlignLeft && this.vertical === PrimitiveAlignment.AlignBottom;
  416. }
  417. }
  418. /**
  419. * Stores information about a Primitive that was intersected
  420. */
  421. export class PrimitiveIntersectedInfo {
  422. constructor(public prim: Prim2DBase, public intersectionLocation: Vector2) {
  423. }
  424. }
  425. /**
  426. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  427. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  428. */
  429. @className("PrimitiveThickness", "BABYLON")
  430. export class PrimitiveThickness {
  431. constructor(parentAccess: () => PrimitiveThickness, changedCallback?: () => void) {
  432. this._parentAccess = parentAccess;
  433. this._changedCallback = changedCallback;
  434. this._pixels = new Array<number>(4);
  435. this._percentages = new Array<number>(4);
  436. this._setType(0, PrimitiveThickness.Auto);
  437. this._setType(1, PrimitiveThickness.Auto);
  438. this._setType(2, PrimitiveThickness.Auto);
  439. this._setType(3, PrimitiveThickness.Auto);
  440. this._pixels[0] = 0;
  441. this._pixels[1] = 0;
  442. this._pixels[2] = 0;
  443. this._pixels[3] = 0;
  444. }
  445. /**
  446. * Set the thickness from a string value
  447. * @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.
  448. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  449. */
  450. public fromString(thickness: string) {
  451. this._clear();
  452. let m = thickness.trim().split(",");
  453. // Special case, one value to apply to all edges
  454. if (m.length === 1 && thickness.indexOf(":") === -1) {
  455. this._setStringValue(m[0], 0, false);
  456. this._setStringValue(m[0], 1, false);
  457. this._setStringValue(m[0], 2, false);
  458. this._setStringValue(m[0], 3, false);
  459. this.onChangeCallback();
  460. return;
  461. }
  462. let res = false;
  463. for (let cm of m) {
  464. res = this._extractString(cm, false) || res;
  465. }
  466. if (!res) {
  467. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  468. }
  469. // Check the margin that weren't set and set them in auto
  470. if ((this._flags & 0x000F) === 0) this._flags |= PrimitiveThickness.Pixel << 0;
  471. if ((this._flags & 0x00F0) === 0) this._flags |= PrimitiveThickness.Pixel << 4;
  472. if ((this._flags & 0x0F00) === 0) this._flags |= PrimitiveThickness.Pixel << 8;
  473. if ((this._flags & 0xF000) === 0) this._flags |= PrimitiveThickness.Pixel << 12;
  474. this.onChangeCallback();
  475. }
  476. /**
  477. * Set the thickness from multiple string
  478. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  479. * @param top the top thickness to set
  480. * @param left the left thickness to set
  481. * @param right the right thickness to set
  482. * @param bottom the bottom thickness to set
  483. */
  484. public fromStrings(top: string, left: string, right: string, bottom: string): PrimitiveThickness {
  485. this._clear();
  486. this._setStringValue(top, 0, false);
  487. this._setStringValue(left, 1, false);
  488. this._setStringValue(right, 2, false);
  489. this._setStringValue(bottom, 3, false);
  490. this.onChangeCallback();
  491. return this;
  492. }
  493. /**
  494. * Set the thickness from pixel values
  495. * @param top the top thickness in pixels to set
  496. * @param left the left thickness in pixels to set
  497. * @param right the right thickness in pixels to set
  498. * @param bottom the bottom thickness in pixels to set
  499. */
  500. public fromPixels(top: number, left: number, right: number, bottom: number): PrimitiveThickness {
  501. this._clear();
  502. this._pixels[0] = top;
  503. this._pixels[1] = left;
  504. this._pixels[2] = right;
  505. this._pixels[3] = bottom;
  506. this.onChangeCallback();
  507. return this;
  508. }
  509. /**
  510. * Apply the same pixel value to all edges
  511. * @param margin the value to set, in pixels.
  512. */
  513. public fromUniformPixels(margin: number): PrimitiveThickness {
  514. this._clear();
  515. this._pixels[0] = margin;
  516. this._pixels[1] = margin;
  517. this._pixels[2] = margin;
  518. this._pixels[3] = margin;
  519. this.onChangeCallback();
  520. return this;
  521. }
  522. public copyFrom(pt: PrimitiveThickness) {
  523. this._clear();
  524. for (let i = 0; i < 4; i++) {
  525. this._pixels[i] = pt._pixels[i];
  526. this._percentages[i] = pt._percentages[i];
  527. }
  528. this._flags = pt._flags;
  529. this.onChangeCallback();
  530. }
  531. /**
  532. * Set all edges in auto
  533. */
  534. public auto(): PrimitiveThickness {
  535. this._clear();
  536. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  537. this._pixels[0] = 0;
  538. this._pixels[1] = 0;
  539. this._pixels[2] = 0;
  540. this._pixels[3] = 0;
  541. this.onChangeCallback();
  542. return this;
  543. }
  544. private _clear() {
  545. this._flags = 0;
  546. this._pixels[0] = 0;
  547. this._pixels[1] = 0;
  548. this._pixels[2] = 0;
  549. this._pixels[3] = 0;
  550. this._percentages[0] = null;
  551. this._percentages[1] = null;
  552. this._percentages[2] = null;
  553. this._percentages[3] = null;
  554. }
  555. private _extractString(value: string, emitChanged: boolean): boolean {
  556. let v = value.trim().toLocaleLowerCase();
  557. if (v.indexOf("top:") === 0) {
  558. v = v.substr(4).trim();
  559. return this._setStringValue(v, 0, emitChanged);
  560. }
  561. if (v.indexOf("left:") === 0) {
  562. v = v.substr(5).trim();
  563. return this._setStringValue(v, 1, emitChanged);
  564. }
  565. if (v.indexOf("right:") === 0) {
  566. v = v.substr(6).trim();
  567. return this._setStringValue(v, 2, emitChanged);
  568. }
  569. if (v.indexOf("bottom:") === 0) {
  570. v = v.substr(7).trim();
  571. return this._setStringValue(v, 3, emitChanged);
  572. }
  573. return false;
  574. }
  575. private _setStringValue(value: string, index: number, emitChanged: boolean): boolean {
  576. // Check for auto
  577. let v = value.trim().toLocaleLowerCase();
  578. if (v === "auto") {
  579. if (this._isType(index, PrimitiveThickness.Auto)) {
  580. return true;
  581. }
  582. this._setType(index, PrimitiveThickness.Auto);
  583. this._pixels[index] = 0;
  584. if (emitChanged) {
  585. this.onChangeCallback();
  586. }
  587. } else if (v === "inherit") {
  588. if (this._isType(index, PrimitiveThickness.Inherit)) {
  589. return true;
  590. }
  591. this._setType(index, PrimitiveThickness.Inherit);
  592. this._pixels[index] = null;
  593. if (emitChanged) {
  594. this.onChangeCallback();
  595. }
  596. } else {
  597. let pI = v.indexOf("%");
  598. // Check for percentage
  599. if (pI !== -1) {
  600. let n = v.substr(0, pI);
  601. let number = Math.round(Number(n)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  602. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number)) {
  603. return true;
  604. }
  605. this._setType(index, PrimitiveThickness.Percentage);
  606. if (isNaN(number)) {
  607. return false;
  608. }
  609. this._percentages[index] = number;
  610. if (emitChanged) {
  611. this.onChangeCallback();
  612. }
  613. return true;
  614. }
  615. // Check for pixel
  616. let n: string;
  617. pI = v.indexOf("px");
  618. if (pI !== -1) {
  619. n = v.substr(0, pI).trim();
  620. } else {
  621. n = v;
  622. }
  623. let number = Number(n);
  624. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  625. return true;
  626. }
  627. if (isNaN(number)) {
  628. return false;
  629. }
  630. this._pixels[index] = number;
  631. this._setType(index, PrimitiveThickness.Pixel);
  632. if (emitChanged) {
  633. this.onChangeCallback();
  634. }
  635. return true;
  636. }
  637. }
  638. private _setPixels(value: number, index: number, emitChanged: boolean) {
  639. // 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
  640. value = Math.round(value);
  641. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  642. return;
  643. }
  644. this._setType(index, PrimitiveThickness.Pixel);
  645. this._pixels[index] = value;
  646. if (emitChanged) {
  647. this.onChangeCallback();
  648. }
  649. }
  650. private _setPercentage(value: number, index: number, emitChanged: boolean) {
  651. // Clip Value to bounds
  652. value = Math.min(1, value);
  653. value = Math.max(0, value);
  654. value = Math.round(value * 100) / 100; // 0.01 precision
  655. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  656. return;
  657. }
  658. this._setType(index, PrimitiveThickness.Percentage);
  659. this._percentages[index] = value;
  660. if (emitChanged) {
  661. this.onChangeCallback();
  662. }
  663. }
  664. private _getStringValue(index: number): string {
  665. let f = (this._flags >> (index * 4)) & 0xF;
  666. switch (f) {
  667. case PrimitiveThickness.Auto:
  668. return "auto";
  669. case PrimitiveThickness.Pixel:
  670. return `${this._pixels[index]}px`;
  671. case PrimitiveThickness.Percentage:
  672. return `${this._percentages[index] * 100}%`;
  673. case PrimitiveThickness.Inherit:
  674. return "inherit";
  675. }
  676. return "";
  677. }
  678. private _isType(index: number, type: number): boolean {
  679. let f = (this._flags >> (index * 4)) & 0xF;
  680. return f === type;
  681. }
  682. private _getType(index: number, processInherit: boolean): number {
  683. let t = (this._flags >> (index * 4)) & 0xF;
  684. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  685. let p = this._parentAccess();
  686. if (p) {
  687. return p._getType(index, true);
  688. }
  689. return PrimitiveThickness.Auto;
  690. }
  691. return t;
  692. }
  693. private _setType(index: number, type: number) {
  694. this._flags &= ~(0xF << (index * 4));
  695. this._flags |= type << (index * 4);
  696. }
  697. public setTop(value: number | string) {
  698. if (typeof value === "string") {
  699. this._setStringValue(value, 0, true);
  700. } else {
  701. this.topPixels = value;
  702. }
  703. }
  704. public setLeft(value: number | string) {
  705. if (typeof value === "string") {
  706. this._setStringValue(value, 1, true);
  707. } else {
  708. this.leftPixels = value;
  709. }
  710. }
  711. public setRight(value: number | string) {
  712. if (typeof value === "string") {
  713. this._setStringValue(value, 2, true);
  714. } else {
  715. this.rightPixels = value;
  716. }
  717. }
  718. public setBottom(value: number | string) {
  719. if (typeof value === "string") {
  720. this._setStringValue(value, 3, true);
  721. } else {
  722. this.bottomPixels = value;
  723. }
  724. }
  725. /**
  726. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  727. */
  728. public get top(): string {
  729. return this._getStringValue(0);
  730. }
  731. public set top(value: string) {
  732. this._setStringValue(value, 0, true);
  733. }
  734. /**
  735. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  736. */
  737. public get left(): string {
  738. return this._getStringValue(1);
  739. }
  740. public set left(value: string) {
  741. this._setStringValue(value, 1, true);
  742. }
  743. /**
  744. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  745. */
  746. public get right(): string {
  747. return this._getStringValue(2);
  748. }
  749. public set right(value: string) {
  750. this._setStringValue(value, 2, true);
  751. }
  752. /**
  753. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  754. */
  755. public get bottom(): string {
  756. return this._getStringValue(3);
  757. }
  758. public set bottom(value: string) {
  759. this._setStringValue(value, 3, true);
  760. }
  761. /**
  762. * Get/set the top thickness in pixel.
  763. */
  764. public get topPixels(): number {
  765. return this._pixels[0];
  766. }
  767. public set topPixels(value: number) {
  768. this._setPixels(value, 0, true);
  769. }
  770. /**
  771. * Get/set the left thickness in pixel.
  772. */
  773. public get leftPixels(): number {
  774. return this._pixels[1];
  775. }
  776. public set leftPixels(value: number) {
  777. this._setPixels(value, 1, true);
  778. }
  779. /**
  780. * Get/set the right thickness in pixel.
  781. */
  782. public get rightPixels(): number {
  783. return this._pixels[2];
  784. }
  785. public set rightPixels(value: number) {
  786. this._setPixels(value, 2, true);
  787. }
  788. /**
  789. * Get/set the bottom thickness in pixel.
  790. */
  791. public get bottomPixels(): number {
  792. return this._pixels[3];
  793. }
  794. public set bottomPixels(value: number) {
  795. this._setPixels(value, 3, true);
  796. }
  797. /**
  798. * Get/set the top thickness in percentage.
  799. * The get will return a valid value only if the edge type is percentage.
  800. * The Set will change the edge mode if needed
  801. */
  802. public get topPercentage(): number {
  803. return this._percentages[0];
  804. }
  805. public set topPercentage(value: number) {
  806. this._setPercentage(value, 0, true);
  807. }
  808. /**
  809. * Get/set the left thickness in percentage.
  810. * The get will return a valid value only if the edge mode is percentage.
  811. * The Set will change the edge mode if needed
  812. */
  813. public get leftPercentage(): number {
  814. return this._percentages[1];
  815. }
  816. public set leftPercentage(value: number) {
  817. this._setPercentage(value, 1, true);
  818. }
  819. /**
  820. * Get/set the right thickness in percentage.
  821. * The get will return a valid value only if the edge mode is percentage.
  822. * The Set will change the edge mode if needed
  823. */
  824. public get rightPercentage(): number {
  825. return this._percentages[2];
  826. }
  827. public set rightPercentage(value: number) {
  828. this._setPercentage(value, 2, true);
  829. }
  830. /**
  831. * Get/set the bottom thickness in percentage.
  832. * The get will return a valid value only if the edge mode is percentage.
  833. * The Set will change the edge mode if needed
  834. */
  835. public get bottomPercentage(): number {
  836. return this._percentages[3];
  837. }
  838. public set bottomPercentage(value: number) {
  839. this._setPercentage(value, 3, true);
  840. }
  841. /**
  842. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  843. */
  844. public get topMode(): number {
  845. return this._getType(0, false);
  846. }
  847. public set topMode(mode: number) {
  848. this._setType(0, mode);
  849. }
  850. /**
  851. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  852. */
  853. public get leftMode(): number {
  854. return this._getType(1, false);
  855. }
  856. public set leftMode(mode: number) {
  857. this._setType(1, mode);
  858. }
  859. /**
  860. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  861. */
  862. public get rightMode(): number {
  863. return this._getType(2, false);
  864. }
  865. public set rightMode(mode: number) {
  866. this._setType(2, mode);
  867. }
  868. /**
  869. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  870. */
  871. public get bottomMode(): number {
  872. return this._getType(3, false);
  873. }
  874. public set bottomMode(mode: number) {
  875. this._setType(3, mode);
  876. }
  877. public get isDefault(): boolean {
  878. return this._flags === 0x1111;
  879. }
  880. private _parentAccess: () => PrimitiveThickness;
  881. private _changedCallback: () => void;
  882. private _pixels: number[];
  883. private _percentages: number[]; // Percentages are in fact stored in a normalized range [0;1] with a 0.01 precision
  884. private _flags: number;
  885. public static Auto = 0x1;
  886. public static Inherit = 0x2;
  887. public static Percentage = 0x4;
  888. public static Pixel = 0x8;
  889. private _computePixels(index: number, sourceArea: Size, emitChanged: boolean) {
  890. let type = this._getType(index, false);
  891. if (type === PrimitiveThickness.Inherit) {
  892. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  893. return;
  894. }
  895. if (type !== PrimitiveThickness.Percentage) {
  896. return;
  897. }
  898. let pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  899. this._pixels[index] = pixels;
  900. if (emitChanged) {
  901. this.onChangeCallback();
  902. }
  903. }
  904. private onChangeCallback() {
  905. if (this._changedCallback) {
  906. this._changedCallback();
  907. }
  908. }
  909. /**
  910. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  911. * @param sourceArea the source area where the content must be sized/positioned
  912. * @param contentSize the content size to position/resize
  913. * @param alignment the alignment setting
  914. * @param dstOffset the position of the content
  915. * @param dstArea the new size of the content
  916. */
  917. public computeWithAlignment(sourceArea: Size, contentSize: Size, alignment: PrimitiveAlignment, dstOffset: Vector2, dstArea: Size, computeLayoutArea = false) {
  918. // Fetch some data
  919. let topType = this._getType(0, true);
  920. let leftType = this._getType(1, true);
  921. let rightType = this._getType(2, true);
  922. let bottomType = this._getType(3, true);
  923. let hasWidth = contentSize && (contentSize.width != null);
  924. let hasHeight = contentSize && (contentSize.height != null);
  925. let width = hasWidth ? contentSize.width : 0;
  926. let height = hasHeight ? contentSize.height : 0;
  927. let isTopAuto = topType === PrimitiveThickness.Auto;
  928. let isLeftAuto = leftType === PrimitiveThickness.Auto;
  929. let isRightAuto = rightType === PrimitiveThickness.Auto;
  930. let isBottomAuto = bottomType === PrimitiveThickness.Auto;
  931. switch (alignment.horizontal) {
  932. case PrimitiveAlignment.AlignLeft:
  933. {
  934. if (isLeftAuto) {
  935. dstOffset.x = 0;
  936. } else {
  937. this._computePixels(1, sourceArea, true);
  938. dstOffset.x = this.leftPixels;
  939. }
  940. dstArea.width = width;
  941. if (computeLayoutArea) {
  942. dstArea.width += this.leftPixels;
  943. }
  944. break;
  945. }
  946. case PrimitiveAlignment.AlignRight:
  947. {
  948. if (isRightAuto) {
  949. dstOffset.x = Math.round(sourceArea.width - width);
  950. } else {
  951. this._computePixels(2, sourceArea, true);
  952. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  953. }
  954. dstArea.width = width;
  955. if (computeLayoutArea) {
  956. dstArea.width += this.rightPixels;
  957. }
  958. break;
  959. }
  960. case PrimitiveAlignment.AlignStretch:
  961. {
  962. if (isLeftAuto) {
  963. dstOffset.x = 0;
  964. } else {
  965. this._computePixels(1, sourceArea, true);
  966. dstOffset.x = this.leftPixels;
  967. }
  968. let right = 0;
  969. if (!isRightAuto) {
  970. this._computePixels(2, sourceArea, true);
  971. right = this.rightPixels;
  972. }
  973. dstArea.width = sourceArea.width - (dstOffset.x + right);
  974. break;
  975. }
  976. case PrimitiveAlignment.AlignCenter:
  977. {
  978. if (!isLeftAuto) {
  979. this._computePixels(1, sourceArea, true);
  980. }
  981. if (!isRightAuto) {
  982. this._computePixels(2, sourceArea, true);
  983. }
  984. let offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  985. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  986. dstArea.width = width;
  987. break;
  988. }
  989. }
  990. switch (alignment.vertical) {
  991. case PrimitiveAlignment.AlignTop:
  992. {
  993. if (isTopAuto) {
  994. dstOffset.y = sourceArea.height - height;
  995. } else {
  996. this._computePixels(0, sourceArea, true);
  997. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  998. }
  999. dstArea.height = height;
  1000. if (computeLayoutArea) {
  1001. dstArea.height += this.topPixels;
  1002. }
  1003. break;
  1004. }
  1005. case PrimitiveAlignment.AlignBottom:
  1006. {
  1007. if (isBottomAuto) {
  1008. dstOffset.y = 0;
  1009. } else {
  1010. this._computePixels(3, sourceArea, true);
  1011. dstOffset.y = this.bottomPixels;
  1012. }
  1013. dstArea.height = height;
  1014. if (computeLayoutArea) {
  1015. dstArea.height += this.bottomPixels;
  1016. }
  1017. break;
  1018. }
  1019. case PrimitiveAlignment.AlignStretch:
  1020. {
  1021. if (isBottomAuto) {
  1022. dstOffset.y = 0;
  1023. } else {
  1024. this._computePixels(3, sourceArea, true);
  1025. dstOffset.y = this.bottomPixels;
  1026. }
  1027. let top = 0;
  1028. if (!isTopAuto) {
  1029. this._computePixels(0, sourceArea, true);
  1030. top = this.topPixels;
  1031. }
  1032. dstArea.height = sourceArea.height - (dstOffset.y + top);
  1033. break;
  1034. }
  1035. case PrimitiveAlignment.AlignCenter:
  1036. {
  1037. if (!isTopAuto) {
  1038. this._computePixels(0, sourceArea, true);
  1039. }
  1040. if (!isBottomAuto) {
  1041. this._computePixels(3, sourceArea, true);
  1042. }
  1043. let offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  1044. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  1045. dstArea.height = height;
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. /**
  1051. * Compute an area and its position considering this thickness properties based on a given source area
  1052. * @param sourceArea the source area
  1053. * @param dstOffset the position of the resulting area
  1054. * @param dstArea the size of the resulting area
  1055. */
  1056. public compute(sourceArea: Size, dstOffset: Vector2, dstArea: Size) {
  1057. this._computePixels(0, sourceArea, true);
  1058. this._computePixels(1, sourceArea, true);
  1059. this._computePixels(2, sourceArea, true);
  1060. this._computePixels(3, sourceArea, true);
  1061. dstOffset.x = this.leftPixels;
  1062. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  1063. dstOffset.y = this.bottomPixels;
  1064. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  1065. }
  1066. /**
  1067. * Compute an area considering this thickness properties based on a given source area
  1068. * @param sourceArea the source area
  1069. * @param result the resulting area
  1070. */
  1071. computeArea(sourceArea: Size, result: Size) {
  1072. this._computePixels(0, sourceArea, true);
  1073. this._computePixels(1, sourceArea, true);
  1074. this._computePixels(2, sourceArea, true);
  1075. this._computePixels(3, sourceArea, true);
  1076. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  1077. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  1078. }
  1079. enlarge(sourceArea: Size, dstOffset: Vector2, enlargedArea: Size) {
  1080. this._computePixels(0, sourceArea, true);
  1081. this._computePixels(1, sourceArea, true);
  1082. this._computePixels(2, sourceArea, true);
  1083. this._computePixels(3, sourceArea, true);
  1084. dstOffset.x = this.leftPixels;
  1085. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  1086. dstOffset.y = this.bottomPixels;
  1087. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  1088. }
  1089. }
  1090. /**
  1091. * Main class used for the Primitive Intersection API
  1092. */
  1093. export class IntersectInfo2D {
  1094. constructor() {
  1095. this.findFirstOnly = false;
  1096. this.intersectHidden = false;
  1097. this.pickPosition = Vector2.Zero();
  1098. }
  1099. // Input settings, to setup before calling an intersection related method
  1100. /**
  1101. * Set the pick position, relative to the primitive where the intersection test is made
  1102. */
  1103. public pickPosition: Vector2;
  1104. /**
  1105. * 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)
  1106. */
  1107. public findFirstOnly: boolean;
  1108. /**
  1109. * If true the intersection test will also be made on hidden primitive (false default)
  1110. */
  1111. public intersectHidden: boolean;
  1112. // Intermediate data, don't use!
  1113. public _globalPickPosition: Vector2;
  1114. public _localPickPosition: Vector2;
  1115. // Output settings, up to date in return of a call to an intersection related method
  1116. /**
  1117. * The topmost intersected primitive
  1118. */
  1119. public topMostIntersectedPrimitive: PrimitiveIntersectedInfo;
  1120. /**
  1121. * The array containing all intersected primitive, in no particular order.
  1122. */
  1123. public intersectedPrimitives: Array<PrimitiveIntersectedInfo>;
  1124. /**
  1125. * true if at least one primitive intersected during the test
  1126. */
  1127. public get isIntersected(): boolean {
  1128. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  1129. }
  1130. public isPrimIntersected(prim: Prim2DBase): Vector2 {
  1131. for (let cur of this.intersectedPrimitives) {
  1132. if (cur.prim === prim) {
  1133. return cur.intersectionLocation;
  1134. }
  1135. }
  1136. return null;
  1137. }
  1138. // Internals, don't use
  1139. public _exit(firstLevel: boolean) {
  1140. if (firstLevel) {
  1141. this._globalPickPosition = null;
  1142. }
  1143. }
  1144. }
  1145. @className("Prim2DBase", "BABYLON")
  1146. /**
  1147. * Base class for a Primitive of the Canvas2D feature
  1148. */
  1149. export class Prim2DBase extends SmartPropertyPrim {
  1150. static PRIM2DBASE_PROPCOUNT: number = 24;
  1151. public static _bigInt = Math.pow(2, 30);
  1152. constructor(settings: {
  1153. parent ?: Prim2DBase,
  1154. id ?: string,
  1155. children ?: Array<Prim2DBase>,
  1156. position ?: Vector2,
  1157. x ?: number,
  1158. y ?: number,
  1159. rotation ?: number,
  1160. scale ?: number,
  1161. scaleX ?: number,
  1162. scaleY ?: number,
  1163. dontInheritParentScale ?: boolean,
  1164. opacity ?: number,
  1165. zOrder ?: number,
  1166. origin ?: Vector2,
  1167. layoutEngine ?: LayoutEngineBase | string,
  1168. isVisible ?: boolean,
  1169. isPickable ?: boolean,
  1170. isContainer ?: boolean,
  1171. childrenFlatZOrder ?: boolean,
  1172. marginTop ?: number | string,
  1173. marginLeft ?: number | string,
  1174. marginRight ?: number | string,
  1175. marginBottom ?: number | string,
  1176. margin ?: number | string,
  1177. marginHAlignment ?: number,
  1178. marginVAlignment ?: number,
  1179. marginAlignment ?: string,
  1180. paddingTop ?: number | string,
  1181. paddingLeft ?: number | string,
  1182. paddingRight ?: number | string,
  1183. paddingBottom ?: number | string,
  1184. padding ?: string,
  1185. }) {
  1186. // Avoid checking every time if the object exists
  1187. if (settings == null) {
  1188. settings = {};
  1189. }
  1190. // BASE CLASS CALL
  1191. super();
  1192. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  1193. let owner: Canvas2D;
  1194. let parent: Prim2DBase;
  1195. if (Prim2DBase._isCanvasInit) {
  1196. owner = <Canvas2D><any>this;
  1197. parent = null;
  1198. this._canvasPreInit(settings);
  1199. } else {
  1200. if (settings.parent != null) {
  1201. parent = settings.parent;
  1202. owner = settings.parent.owner;
  1203. if (!owner) {
  1204. throw new Error(`Parent ${parent.id} of ${settings.id} doesn't have a valid owner!`);
  1205. }
  1206. if (!(this instanceof Group2D) && !(this instanceof Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  1207. 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");
  1208. }
  1209. }
  1210. }
  1211. // Fields initialization
  1212. this._layoutEngine = CanvasLayoutEngine.Singleton;
  1213. this._size = null; //Size.Zero();
  1214. this._scale = new Vector2(1, 1);
  1215. this._actualSize = null;
  1216. this._boundingSize = Size.Zero();
  1217. this._layoutArea = Size.Zero();
  1218. this._layoutAreaPos = null;
  1219. this._layoutBoundingInfo = null;
  1220. this._marginOffset = Vector2.Zero();
  1221. this._paddingOffset = Vector2.Zero();
  1222. this._parentPaddingOffset = Vector2.Zero();
  1223. this._parentContentArea = Size.Zero();
  1224. this._lastAutoSizeArea = Size.Zero();
  1225. this._contentArea = new Size(null, null);
  1226. this._pointerEventObservable = new Observable<PrimitivePointerInfo>();
  1227. this._boundingInfo = new BoundingInfo2D();
  1228. this._owner = owner;
  1229. this._parent = null;
  1230. this._margin = null;
  1231. this._padding = null;
  1232. this._marginAlignment = null;
  1233. this._id = settings.id;
  1234. this._children = new Array<Prim2DBase>();
  1235. this._localTransform = new Matrix();
  1236. this._globalTransform = null;
  1237. this._invGlobalTransform = null;
  1238. this._globalTransformProcessStep = 0;
  1239. this._globalTransformStep = 0;
  1240. this._renderGroup = null;
  1241. this._primLinearPosition = 0;
  1242. this._manualZOrder = null;
  1243. this._zOrder = 0;
  1244. this._zMax = 0;
  1245. this._firstZDirtyIndex = Prim2DBase._bigInt;
  1246. this._actualOpacity = 0;
  1247. this._actualScale = Vector2.Zero();
  1248. let isPickable = true;
  1249. let isContainer = true;
  1250. if (settings.isPickable !== undefined) {
  1251. isPickable = settings.isPickable;
  1252. }
  1253. if (settings.isContainer !== undefined) {
  1254. isContainer = settings.isContainer;
  1255. }
  1256. if (settings.dontInheritParentScale) {
  1257. this._setFlags(SmartPropertyPrim.flagDontInheritParentScale);
  1258. }
  1259. this._setFlags((isPickable ? SmartPropertyPrim.flagIsPickable : 0) | SmartPropertyPrim.flagBoundingInfoDirty | SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? SmartPropertyPrim.flagIsContainer : 0) | SmartPropertyPrim.flagActualScaleDirty | SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  1260. if (settings.opacity != null) {
  1261. this._opacity = settings.opacity;
  1262. } else {
  1263. this._opacity = 1;
  1264. }
  1265. this._updateRenderMode();
  1266. if (settings.childrenFlatZOrder) {
  1267. this._setFlags(SmartPropertyPrim.flagChildrenFlatZOrder);
  1268. }
  1269. // If the parent is given, initialize the hierarchy/owner related data
  1270. if (parent != null) {
  1271. parent.addChild(this);
  1272. this._hierarchyDepth = parent._hierarchyDepth + 1;
  1273. this._patchHierarchy(parent.owner);
  1274. }
  1275. // If it's a group, detect its own states
  1276. if (this.owner && this instanceof Group2D) {
  1277. var group: any = this;
  1278. group.detectGroupStates();
  1279. }
  1280. // Time to insert children if some are specified
  1281. if (settings.children != null) {
  1282. for (let child of settings.children) {
  1283. this.addChild(child);
  1284. // Good time to patch the hierarchy, it won't go very far if there's no need to
  1285. if (this.owner != null) {
  1286. child._patchHierarchy(this.owner);
  1287. }
  1288. }
  1289. }
  1290. if (settings.zOrder != null) {
  1291. this.zOrder = settings.zOrder;
  1292. }
  1293. // Set the model related properties
  1294. if (settings.position != null) {
  1295. this.position = settings.position;
  1296. }
  1297. else if (settings.x != null || settings.y != null) {
  1298. this.position = new Vector2(settings.x || 0, settings.y || 0);
  1299. } else {
  1300. this._position = null;
  1301. }
  1302. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  1303. if (settings.scale != null) {
  1304. this.scale = settings.scale;
  1305. } else {
  1306. if (settings.scaleX != null) {
  1307. this.scaleX = settings.scaleX;
  1308. }
  1309. if (settings.scaleY != null) {
  1310. this.scaleY = settings.scaleY;
  1311. }
  1312. }
  1313. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  1314. this.origin = settings.origin || new Vector2(0.5, 0.5);
  1315. // Layout Engine
  1316. if (settings.layoutEngine != null) {
  1317. if (typeof settings.layoutEngine === "string") {
  1318. let name = (<string>settings.layoutEngine).toLocaleLowerCase().trim();
  1319. if (name === "canvas" || name === "canvaslayoutengine") {
  1320. this.layoutEngine = CanvasLayoutEngine.Singleton;
  1321. } else if (name.indexOf("stackpanel") === 0 || name.indexOf("horizontalstackpanel") === 0) {
  1322. this.layoutEngine = StackPanelLayoutEngine.Horizontal;
  1323. } else if (name.indexOf("verticalstackpanel") === 0) {
  1324. this.layoutEngine = StackPanelLayoutEngine.Vertical;
  1325. }
  1326. } else if (settings.layoutEngine instanceof LayoutEngineBase) {
  1327. this.layoutEngine = <LayoutEngineBase>settings.layoutEngine;
  1328. }
  1329. }
  1330. // Set the layout/margin stuffs
  1331. if (settings.marginTop) {
  1332. this.margin.setTop(settings.marginTop);
  1333. }
  1334. if (settings.marginLeft) {
  1335. this.margin.setLeft(settings.marginLeft);
  1336. }
  1337. if (settings.marginRight) {
  1338. this.margin.setRight(settings.marginRight);
  1339. }
  1340. if (settings.marginBottom) {
  1341. this.margin.setBottom(settings.marginBottom);
  1342. }
  1343. if (settings.margin) {
  1344. if (typeof settings.margin === "string") {
  1345. this.margin.fromString(<string>settings.margin);
  1346. } else {
  1347. this.margin.fromUniformPixels(<number>settings.margin);
  1348. }
  1349. }
  1350. if (settings.marginHAlignment) {
  1351. this.marginAlignment.horizontal = settings.marginHAlignment;
  1352. }
  1353. if (settings.marginVAlignment) {
  1354. this.marginAlignment.vertical = settings.marginVAlignment;
  1355. }
  1356. if (settings.marginAlignment) {
  1357. this.marginAlignment.fromString(settings.marginAlignment);
  1358. }
  1359. if (settings.paddingTop) {
  1360. this.padding.setTop(settings.paddingTop);
  1361. }
  1362. if (settings.paddingLeft) {
  1363. this.padding.setLeft(settings.paddingLeft);
  1364. }
  1365. if (settings.paddingRight) {
  1366. this.padding.setRight(settings.paddingRight);
  1367. }
  1368. if (settings.paddingBottom) {
  1369. this.padding.setBottom(settings.paddingBottom);
  1370. }
  1371. if (settings.padding) {
  1372. this.padding.fromString(settings.padding);
  1373. }
  1374. // Dirty layout and positioning
  1375. this._parentLayoutDirty();
  1376. this._positioningDirty();
  1377. }
  1378. public get actionManager(): ActionManager {
  1379. if (!this._actionManager) {
  1380. this._actionManager = new ActionManager(this.owner.scene);
  1381. }
  1382. return this._actionManager;
  1383. }
  1384. /**
  1385. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  1386. * @param predicate the predicate to test on each parent
  1387. * @return the first primitive where the predicate was successful
  1388. */
  1389. public traverseUp(predicate: (p: Prim2DBase) => boolean): Prim2DBase {
  1390. let p: Prim2DBase = this;
  1391. while (p != null) {
  1392. if (predicate(p)) {
  1393. return p;
  1394. }
  1395. p = p._parent;
  1396. }
  1397. return null;
  1398. }
  1399. /**
  1400. * Retrieve the owner Canvas2D
  1401. */
  1402. public get owner(): Canvas2D {
  1403. return this._owner;
  1404. }
  1405. /**
  1406. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  1407. */
  1408. public get parent(): Prim2DBase {
  1409. return this._parent;
  1410. }
  1411. /**
  1412. * The array of direct children primitives
  1413. */
  1414. public get children(): Prim2DBase[] {
  1415. return this._children;
  1416. }
  1417. /**
  1418. * The identifier of this primitive, may not be unique, it's for information purpose only
  1419. */
  1420. public get id(): string {
  1421. return this._id;
  1422. }
  1423. /**
  1424. * Metadata of the position property
  1425. */
  1426. public static positionProperty: Prim2DPropInfo;
  1427. /**
  1428. * Metadata of the left property
  1429. */
  1430. public static xProperty: Prim2DPropInfo;
  1431. /**
  1432. * Metadata of the bottom property
  1433. */
  1434. public static yProperty: Prim2DPropInfo;
  1435. /**
  1436. * Metadata of the actualPosition property
  1437. */
  1438. public static actualPositionProperty: Prim2DPropInfo;
  1439. /**
  1440. * Metadata of the actualX (Left) property
  1441. */
  1442. public static actualXProperty: Prim2DPropInfo;
  1443. /**
  1444. * Metadata of the actualY (Bottom) property
  1445. */
  1446. public static actualYProperty: Prim2DPropInfo;
  1447. /**
  1448. * Metadata of the size property
  1449. */
  1450. public static sizeProperty: Prim2DPropInfo;
  1451. /**
  1452. * Metadata of the width property
  1453. */
  1454. public static widthProperty: Prim2DPropInfo;
  1455. /**
  1456. * Metadata of the height property
  1457. */
  1458. public static heightProperty: Prim2DPropInfo;
  1459. /**
  1460. * Metadata of the rotation property
  1461. */
  1462. public static rotationProperty: Prim2DPropInfo;
  1463. /**
  1464. * Metadata of the scale property
  1465. */
  1466. public static scaleProperty: Prim2DPropInfo;
  1467. /**
  1468. * Metadata of the actualSize property
  1469. */
  1470. public static actualSizeProperty: Prim2DPropInfo;
  1471. /**
  1472. * Metadata of the actualWidth property
  1473. */
  1474. public static actualWidthProperty: Prim2DPropInfo;
  1475. /**
  1476. * Metadata of the actualHeight property
  1477. */
  1478. public static actualHeightProperty: Prim2DPropInfo;
  1479. /**
  1480. * Metadata of the origin property
  1481. */
  1482. public static originProperty: Prim2DPropInfo;
  1483. /**
  1484. * Metadata of the levelVisible property
  1485. */
  1486. public static levelVisibleProperty: Prim2DPropInfo;
  1487. /**
  1488. * Metadata of the isVisible property
  1489. */
  1490. public static isVisibleProperty: Prim2DPropInfo;
  1491. /**
  1492. * Metadata of the zOrder property
  1493. */
  1494. public static zOrderProperty: Prim2DPropInfo;
  1495. /**
  1496. * Metadata of the margin property
  1497. */
  1498. public static marginProperty: Prim2DPropInfo;
  1499. /**
  1500. * Metadata of the margin property
  1501. */
  1502. public static paddingProperty: Prim2DPropInfo;
  1503. /**
  1504. * Metadata of the hAlignment property
  1505. */
  1506. public static marginAlignmentProperty: Prim2DPropInfo;
  1507. /**
  1508. * Metadata of the opacity property
  1509. */
  1510. public static opacityProperty: Prim2DPropInfo;
  1511. /**
  1512. * Metadata of the scaleX property
  1513. */
  1514. public static scaleXProperty: Prim2DPropInfo;
  1515. /**
  1516. * Metadata of the scaleY property
  1517. */
  1518. public static scaleYProperty: Prim2DPropInfo;
  1519. @instanceLevelProperty(1, pi => Prim2DBase.actualPositionProperty = pi, false, false, true)
  1520. /**
  1521. * 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
  1522. */
  1523. public get actualPosition(): Vector2 {
  1524. if (this._actualPosition != null) {
  1525. return this._actualPosition;
  1526. }
  1527. if (this._position != null) {
  1528. return this._position;
  1529. }
  1530. // At least return 0,0, we can't return null on actualPosition
  1531. return Prim2DBase._nullPosition;
  1532. }
  1533. private static _nullPosition = Vector2.Zero();
  1534. /**
  1535. * DO NOT INVOKE for internal purpose only
  1536. */
  1537. public set actualPosition(val: Vector2) {
  1538. this._actualPosition = val;
  1539. }
  1540. /**
  1541. * Shortcut to actualPosition.x
  1542. */
  1543. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, pi => Prim2DBase.actualXProperty = pi, false, false, true)
  1544. public get actualX(): number {
  1545. return this.actualPosition.x;
  1546. }
  1547. public set actualX(val: number) {
  1548. this._actualPosition.x = val;
  1549. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, this._actualPosition);
  1550. }
  1551. /**
  1552. * Shortcut to actualPosition.y
  1553. */
  1554. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, pi => Prim2DBase.actualYProperty = pi, false, false, true)
  1555. public get actualY(): number {
  1556. return this.actualPosition.y;
  1557. }
  1558. public set actualY(val: number) {
  1559. this._actualPosition.y = val;
  1560. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, this._actualPosition);
  1561. }
  1562. /**
  1563. * Position of the primitive, relative to its parent.
  1564. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  1565. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  1566. * Setting this property may have no effect is specific alignment are in effect.
  1567. */
  1568. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, pi => Prim2DBase.positionProperty = pi, false, false, true)
  1569. public get position(): Vector2 {
  1570. return this._position || Prim2DBase._nullPosition;
  1571. }
  1572. public set position(value: Vector2) {
  1573. if (!this._checkPositionChange()) {
  1574. return;
  1575. }
  1576. this._position = value;
  1577. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  1578. }
  1579. /**
  1580. * Direct access to the position.x value of the primitive
  1581. * Use this property when you only want to change one component of the position property
  1582. */
  1583. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, pi => Prim2DBase.xProperty = pi, false, false, true)
  1584. public get x(): number {
  1585. if (!this._position) {
  1586. return null;
  1587. }
  1588. return this._position.x;
  1589. }
  1590. public set x(value: number) {
  1591. if (!this._checkPositionChange()) {
  1592. return;
  1593. }
  1594. if (!this._position) {
  1595. this._position = Vector2.Zero();
  1596. }
  1597. if (this._position.x === value) {
  1598. return;
  1599. }
  1600. this._position.x = value;
  1601. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  1602. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  1603. }
  1604. /**
  1605. * Direct access to the position.y value of the primitive
  1606. * Use this property when you only want to change one component of the position property
  1607. */
  1608. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, pi => Prim2DBase.yProperty = pi, false, false, true)
  1609. public get y(): number {
  1610. if (!this._position) {
  1611. return null;
  1612. }
  1613. return this._position.y;
  1614. }
  1615. public set y(value: number) {
  1616. if (!this._checkPositionChange()) {
  1617. return;
  1618. }
  1619. if (!this._position) {
  1620. this._position = Vector2.Zero();
  1621. }
  1622. if (this._position.y === value) {
  1623. return;
  1624. }
  1625. this._position.y = value;
  1626. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  1627. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  1628. }
  1629. private static boundinbBoxReentrency = false;
  1630. protected static nullSize = Size.Zero();
  1631. /**
  1632. * Size of the primitive or its bounding area
  1633. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  1634. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  1635. */
  1636. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, pi => Prim2DBase.sizeProperty = pi, false, true)
  1637. public get size(): Size {
  1638. if (!this._size || this._size.width == null || this._size.height == null) {
  1639. if (Prim2DBase.boundinbBoxReentrency) {
  1640. return Prim2DBase.nullSize;
  1641. }
  1642. if (!this._isFlagSet(SmartPropertyPrim.flagBoundingInfoDirty)) {
  1643. return this._boundingSize;
  1644. }
  1645. Prim2DBase.boundinbBoxReentrency = true;
  1646. let b = this.boundingInfo;
  1647. Prim2DBase.boundinbBoxReentrency = false;
  1648. return this._boundingSize;
  1649. }
  1650. return this._size;
  1651. }
  1652. public set size(value: Size) {
  1653. this._size = value;
  1654. }
  1655. /**
  1656. * Direct access to the size.width value of the primitive
  1657. * Use this property when you only want to change one component of the size property
  1658. */
  1659. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, pi => Prim2DBase.widthProperty = pi, false, true)
  1660. public get width(): number {
  1661. if (!this.size) {
  1662. return null;
  1663. }
  1664. return this.size.width;
  1665. }
  1666. public set width(value: number) {
  1667. if (this.size && this.size.width === value) {
  1668. return;
  1669. }
  1670. if (!this.size) {
  1671. this.size = new Size(value, 0);
  1672. } else {
  1673. this.size.width = value;
  1674. }
  1675. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  1676. this._positioningDirty();
  1677. }
  1678. /**
  1679. * Direct access to the size.height value of the primitive
  1680. * Use this property when you only want to change one component of the size property
  1681. */
  1682. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, pi => Prim2DBase.heightProperty = pi, false, true)
  1683. public get height(): number {
  1684. if (!this.size) {
  1685. return null;
  1686. }
  1687. return this.size.height;
  1688. }
  1689. public set height(value: number) {
  1690. if (this.size && this.size.height === value) {
  1691. return;
  1692. }
  1693. if (!this.size) {
  1694. this.size = new Size(0, value);
  1695. } else {
  1696. this.size.height = value;
  1697. }
  1698. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  1699. this._positioningDirty();
  1700. }
  1701. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, pi => Prim2DBase.rotationProperty = pi, false, true)
  1702. /**
  1703. * Rotation of the primitive, in radian, along the Z axis
  1704. */
  1705. public get rotation(): number {
  1706. return this._rotation;
  1707. }
  1708. public set rotation(value: number) {
  1709. this._rotation = value;
  1710. }
  1711. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, pi => Prim2DBase.scaleProperty = pi, false, true)
  1712. /**
  1713. * 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.
  1714. */
  1715. public set scale(value: number) {
  1716. this._scale.x = this._scale.y = value;
  1717. this._setFlags(SmartPropertyPrim.flagActualScaleDirty);
  1718. this._spreadActualScaleDirty();
  1719. }
  1720. public get scale(): number {
  1721. return this._scale.x;
  1722. }
  1723. /**
  1724. * Return the size of the primitive as it's being rendered into the target.
  1725. * 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.
  1726. * BEWARE: don't use the setter, it's for internal purpose only
  1727. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  1728. */
  1729. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, pi => Prim2DBase.actualSizeProperty = pi, false, true)
  1730. public get actualSize(): Size {
  1731. if (this._actualSize) {
  1732. return this._actualSize;
  1733. }
  1734. return this._size;
  1735. }
  1736. public set actualSize(value: Size) {
  1737. if (this._actualSize.equals(value)) {
  1738. return;
  1739. }
  1740. this._actualSize = value;
  1741. }
  1742. /**
  1743. * Shortcut to actualSize.width
  1744. */
  1745. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, pi => Prim2DBase.actualWidthProperty = pi, false, true)
  1746. public get actualWidth(): number {
  1747. return this.actualSize.width;
  1748. }
  1749. public set actualWidth(val: number) {
  1750. this._actualSize.width = val;
  1751. this._triggerPropertyChanged(Prim2DBase.actualSizeProperty, this._actualSize);
  1752. }
  1753. /**
  1754. * Shortcut to actualPosition.height
  1755. */
  1756. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, pi => Prim2DBase.actualHeightProperty = pi, false, true)
  1757. public get actualHeight(): number {
  1758. return this.actualSize.width;
  1759. }
  1760. public set actualHeight(val: number) {
  1761. this._actualSize.height = val;
  1762. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, this._actualSize);
  1763. }
  1764. public get actualZOffset(): number {
  1765. if (this._manualZOrder!=null) {
  1766. return this._manualZOrder;
  1767. }
  1768. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  1769. this._updateZOrder();
  1770. }
  1771. return (1 - this._zOrder);
  1772. }
  1773. /**
  1774. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  1775. * The Primitive's size won't be less than specified.
  1776. * The default value depends of the Primitive type
  1777. */
  1778. public get minSize(): Size {
  1779. return this._minSize;
  1780. }
  1781. public set minSize(value: Size) {
  1782. if (this._minSize && value && this._minSize.equals(value)) {
  1783. return;
  1784. }
  1785. this._minSize = value;
  1786. this._parentLayoutDirty();
  1787. }
  1788. /**
  1789. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  1790. * The Primitive's size won't be more than specified.
  1791. * The default value depends of the Primitive type
  1792. */
  1793. public get maxSize(): Size {
  1794. return this._maxSize;
  1795. }
  1796. public set maxSize(value: Size) {
  1797. if (this._maxSize && value && this._maxSize.equals(value)) {
  1798. return;
  1799. }
  1800. this._maxSize = value;
  1801. this._parentLayoutDirty();
  1802. }
  1803. /**
  1804. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  1805. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  1806. * For instance:
  1807. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  1808. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  1809. * 0,1 means the center is top/left
  1810. * @returns The normalized center.
  1811. */
  1812. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, pi => Prim2DBase.originProperty = pi, false, true)
  1813. public get origin(): Vector2 {
  1814. return this._origin;
  1815. }
  1816. public set origin(value: Vector2) {
  1817. this._origin = value;
  1818. }
  1819. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, pi => Prim2DBase.levelVisibleProperty = pi)
  1820. /**
  1821. * 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.
  1822. * Default is true, setting to false will hide this primitive and its children.
  1823. */
  1824. public get levelVisible(): boolean {
  1825. return this._isFlagSet(SmartPropertyPrim.flagLevelVisible);
  1826. }
  1827. public set levelVisible(value: boolean) {
  1828. this._changeFlags(SmartPropertyPrim.flagLevelVisible, value);
  1829. }
  1830. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, pi => Prim2DBase.isVisibleProperty = pi)
  1831. /**
  1832. * Use ONLY THE GETTER to determine if the primitive is visible or not.
  1833. * The Setter is for internal purpose only!
  1834. */
  1835. public get isVisible(): boolean {
  1836. return this._isFlagSet(SmartPropertyPrim.flagIsVisible);
  1837. }
  1838. public set isVisible(value: boolean) {
  1839. this._changeFlags(SmartPropertyPrim.flagIsVisible, value);
  1840. }
  1841. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, pi => Prim2DBase.zOrderProperty = pi)
  1842. /**
  1843. * You can override the default Z Order through this property, but most of the time the default behavior is acceptable
  1844. */
  1845. public get zOrder(): number {
  1846. return this._manualZOrder;
  1847. }
  1848. public set zOrder(value: number) {
  1849. if (this._manualZOrder === value) {
  1850. return;
  1851. }
  1852. this._manualZOrder = value;
  1853. this.onZOrderChanged();
  1854. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  1855. this._actualZOrderChangedObservable.notifyObservers(value);
  1856. }
  1857. }
  1858. public get isManualZOrder(): boolean {
  1859. return this._manualZOrder != null;
  1860. }
  1861. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, pi => Prim2DBase.marginProperty = pi)
  1862. /**
  1863. * You can get/set a margin on the primitive through this property
  1864. * @returns the margin object, if there was none, a default one is created and returned
  1865. */
  1866. public get margin(): PrimitiveThickness {
  1867. if (!this._margin) {
  1868. this._margin = new PrimitiveThickness(() => {
  1869. if (!this.parent) {
  1870. return null;
  1871. }
  1872. return this.parent.margin;
  1873. }, () => this._positioningDirty());
  1874. }
  1875. return this._margin;
  1876. }
  1877. public set margin(value: PrimitiveThickness) {
  1878. this.margin.copyFrom(value);
  1879. }
  1880. /**
  1881. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  1882. */
  1883. public get _hasMargin(): boolean {
  1884. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  1885. }
  1886. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, pi => Prim2DBase.paddingProperty = pi)
  1887. /**
  1888. * You can get/set a margin on the primitive through this property
  1889. * @returns the margin object, if there was none, a default one is created and returned
  1890. */
  1891. public get padding(): PrimitiveThickness {
  1892. if (!this._padding) {
  1893. this._padding = new PrimitiveThickness(() => {
  1894. if (!this.parent) {
  1895. return null;
  1896. }
  1897. return this.parent.padding;
  1898. }, () => this._positioningDirty());
  1899. }
  1900. return this._padding;
  1901. }
  1902. public set padding(value: PrimitiveThickness) {
  1903. this.padding.copyFrom(value);
  1904. }
  1905. private get _hasPadding(): boolean {
  1906. return this._padding !== null && !this._padding.isDefault;
  1907. }
  1908. @dynamicLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, pi => Prim2DBase.marginAlignmentProperty = pi)
  1909. /**
  1910. * You can get/set the margin alignment through this property
  1911. */
  1912. public get marginAlignment(): PrimitiveAlignment {
  1913. if (!this._marginAlignment) {
  1914. this._marginAlignment = new PrimitiveAlignment(() => this._positioningDirty());
  1915. }
  1916. return this._marginAlignment;
  1917. }
  1918. public set marginAlignment(value: PrimitiveAlignment) {
  1919. this.marginAlignment.copyFrom(value);
  1920. }
  1921. /**
  1922. * Check if there a marginAlignment specified (non null and not default)
  1923. */
  1924. public get _hasMarginAlignment(): boolean {
  1925. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  1926. }
  1927. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, pi => Prim2DBase.opacityProperty = pi)
  1928. /**
  1929. * Get/set the opacity of the whole primitive
  1930. */
  1931. public get opacity(): number {
  1932. return this._opacity;
  1933. }
  1934. public set opacity(value: number) {
  1935. if (value < 0) {
  1936. value = 0;
  1937. } else if (value > 1) {
  1938. value = 1;
  1939. }
  1940. if (this._opacity === value) {
  1941. return;
  1942. }
  1943. this._opacity = value;
  1944. this._setFlags(SmartPropertyPrim.flagActualOpacityDirty);
  1945. this._spreadActualOpacityChanged();
  1946. this._updateRenderMode();
  1947. }
  1948. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, pi => Prim2DBase.scaleXProperty = pi, false, true)
  1949. /**
  1950. * Scale applied on the X axis of the primitive
  1951. */
  1952. public set scaleX(value: number) {
  1953. this._scale.x = value;
  1954. this._setFlags(SmartPropertyPrim.flagActualScaleDirty);
  1955. this._spreadActualScaleDirty();
  1956. }
  1957. public get scaleX(): number {
  1958. return this._scale.x;
  1959. }
  1960. @instanceLevelProperty(SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, pi => Prim2DBase.scaleYProperty = pi, false, true)
  1961. /**
  1962. * Scale applied on the Y axis of the primitive
  1963. */
  1964. public set scaleY(value: number) {
  1965. this._scale.y = value;
  1966. this._setFlags(SmartPropertyPrim.flagActualScaleDirty);
  1967. this._spreadActualScaleDirty();
  1968. }
  1969. public get scaleY(): number {
  1970. return this._scale.y;
  1971. }
  1972. private _spreadActualScaleDirty() {
  1973. for (let child of this._children) {
  1974. child._setFlags(SmartPropertyPrim.flagActualScaleDirty);
  1975. child._spreadActualScaleDirty();
  1976. }
  1977. }
  1978. /**
  1979. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  1980. */
  1981. public get actualScale(): Vector2 {
  1982. if (this._isFlagSet(SmartPropertyPrim.flagActualScaleDirty)) {
  1983. let cur = this._isFlagSet(SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  1984. let sx = this.scaleX;
  1985. let sy = this.scaleY;
  1986. while (cur) {
  1987. sx *= cur.scaleX;
  1988. sy *= cur.scaleY;
  1989. cur = cur._isFlagSet(SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  1990. }
  1991. this._actualScale.copyFromFloats(sx, sy);
  1992. this._clearFlags(SmartPropertyPrim.flagActualScaleDirty);
  1993. }
  1994. return this._actualScale;
  1995. }
  1996. /**
  1997. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  1998. */
  1999. public get actualScaleX(): number {
  2000. return this.actualScale.x;
  2001. }
  2002. /**
  2003. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  2004. */
  2005. public get actualScaleY(): number {
  2006. return this.actualScale.y;
  2007. }
  2008. /**
  2009. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  2010. */
  2011. public get actualOpacity(): number {
  2012. if (this._isFlagSet(SmartPropertyPrim.flagActualOpacityDirty)) {
  2013. let cur = this.parent;
  2014. let op = this.opacity;
  2015. while (cur) {
  2016. op *= cur.opacity;
  2017. cur = cur.parent;
  2018. }
  2019. this._actualOpacity = op;
  2020. this._clearFlags(SmartPropertyPrim.flagActualOpacityDirty);
  2021. }
  2022. return this._actualOpacity;
  2023. }
  2024. /**
  2025. * Get/set the layout engine to use for this primitive.
  2026. * The default layout engine is the CanvasLayoutEngine.
  2027. */
  2028. public get layoutEngine(): LayoutEngineBase {
  2029. if (!this._layoutEngine) {
  2030. this._layoutEngine = CanvasLayoutEngine.Singleton;
  2031. }
  2032. return this._layoutEngine;
  2033. }
  2034. public set layoutEngine(value: LayoutEngineBase) {
  2035. if (this._layoutEngine === value) {
  2036. return;
  2037. }
  2038. this._changeLayoutEngine(value);
  2039. }
  2040. /**
  2041. * Get/set the layout are of this primitive.
  2042. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  2043. * The setter should only be called by a Layout Engine class.
  2044. */
  2045. public get layoutArea(): Size {
  2046. return this._layoutArea;
  2047. }
  2048. public set layoutArea(val: Size) {
  2049. if (this._layoutArea.equals(val)) {
  2050. return;
  2051. }
  2052. this._positioningDirty();
  2053. if (this.parent) {
  2054. this.parent._setFlags(SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  2055. }
  2056. this._layoutArea = val;
  2057. }
  2058. /**
  2059. * Get/set the layout area position (relative to the parent primitive).
  2060. * The setter should only be called by a Layout Engine class.
  2061. */
  2062. public get layoutAreaPos(): Vector2 {
  2063. return this._layoutAreaPos || Prim2DBase._nullPosition;
  2064. }
  2065. public set layoutAreaPos(val: Vector2) {
  2066. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  2067. return;
  2068. }
  2069. if (this.parent) {
  2070. this.parent._setFlags(SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  2071. }
  2072. this._positioningDirty();
  2073. this._layoutAreaPos = val;
  2074. }
  2075. /**
  2076. * Define if the Primitive can be subject to intersection test or not (default is true)
  2077. */
  2078. public get isPickable(): boolean {
  2079. return this._isFlagSet(SmartPropertyPrim.flagIsPickable);
  2080. }
  2081. public set isPickable(value: boolean) {
  2082. this._changeFlags(SmartPropertyPrim.flagIsPickable, value);
  2083. }
  2084. /**
  2085. * Define if the Primitive acts as a container or not
  2086. * A container will encapsulate its children for interaction event.
  2087. * If it's not a container events will be process down to children if the primitive is not pickable.
  2088. * Default value is true
  2089. */
  2090. public get isContainer(): boolean {
  2091. return this._isFlagSet(SmartPropertyPrim.flagIsContainer);
  2092. }
  2093. public set isContainer(value: boolean) {
  2094. this._changeFlags(SmartPropertyPrim.flagIsContainer, value);
  2095. }
  2096. /**
  2097. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  2098. */
  2099. public get hierarchyDepth(): number {
  2100. return this._hierarchyDepth;
  2101. }
  2102. /**
  2103. * Retrieve the Group that is responsible to render this primitive
  2104. */
  2105. public get renderGroup(): Group2D {
  2106. return this._renderGroup;
  2107. }
  2108. /**
  2109. * Get the global transformation matrix of the primitive
  2110. */
  2111. public get globalTransform(): Matrix {
  2112. this._updateLocalTransform();
  2113. return this._globalTransform;
  2114. }
  2115. /**
  2116. * return the global position of the primitive, relative to its canvas
  2117. */
  2118. public getGlobalPosition(): Vector2 {
  2119. let v = new Vector2(0, 0);
  2120. this.getGlobalPositionByRef(v);
  2121. return v;
  2122. }
  2123. /**
  2124. * return the global position of the primitive, relative to its canvas
  2125. * @param v the valid Vector2 object where the global position will be stored
  2126. */
  2127. public getGlobalPositionByRef(v: Vector2) {
  2128. v.x = this.globalTransform.m[12];
  2129. v.y = this.globalTransform.m[13];
  2130. }
  2131. /**
  2132. * Get invert of the global transformation matrix of the primitive
  2133. */
  2134. public get invGlobalTransform(): Matrix {
  2135. this._updateLocalTransform();
  2136. return this._invGlobalTransform;
  2137. }
  2138. /**
  2139. * Get the local transformation of the primitive
  2140. */
  2141. public get localTransform(): Matrix {
  2142. this._updateLocalTransform();
  2143. return this._localTransform;
  2144. }
  2145. private static _bMax = Vector2.Zero();
  2146. private static _tpsBB = new BoundingInfo2D();
  2147. /**
  2148. * Get the boundingInfo associated to the primitive and its children.
  2149. * The value is supposed to be always up to date
  2150. */
  2151. public get boundingInfo(): BoundingInfo2D {
  2152. if (this._isFlagSet(SmartPropertyPrim.flagBoundingInfoDirty)) {
  2153. if (this.owner) {
  2154. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  2155. }
  2156. if (this.isSizedByContent) {
  2157. this._boundingInfo.clear();
  2158. } else {
  2159. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  2160. }
  2161. let bi = this._boundingInfo;
  2162. var tps = new BoundingInfo2D();
  2163. for (let curChild of this._children) {
  2164. let bb = curChild.boundingInfo;
  2165. bb.transformToRef(curChild.localTransform, tps);
  2166. bi.unionToRef(tps, bi);
  2167. }
  2168. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  2169. this._boundingSize.copyFromFloats(
  2170. (!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width,
  2171. (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  2172. this._clearFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  2173. }
  2174. return this._boundingInfo;
  2175. }
  2176. /**
  2177. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  2178. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  2179. */
  2180. public get layoutBoundingInfo(): BoundingInfo2D {
  2181. if (this._isFlagSet(SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  2182. if (!this._layoutBoundingInfo) {
  2183. this._layoutBoundingInfo = new BoundingInfo2D();
  2184. }
  2185. if (this.isSizedByContent) {
  2186. this._layoutBoundingInfo.clear();
  2187. } else {
  2188. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  2189. }
  2190. let bi = this._layoutBoundingInfo;
  2191. var tps = new BoundingInfo2D();
  2192. for (let curChild of this._children) {
  2193. let bb: BoundingInfo2D;
  2194. if (curChild._layoutAreaPos) {
  2195. let s = curChild._layoutArea;
  2196. BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase._tpsBB);
  2197. bb = Prim2DBase._tpsBB;
  2198. } else {
  2199. bb = curChild.boundingInfo;
  2200. }
  2201. bb.transformToRef(curChild.localTransform, tps);
  2202. bi.unionToRef(tps, bi);
  2203. }
  2204. this._clearFlags(SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  2205. }
  2206. return this._layoutBoundingInfo;
  2207. }
  2208. /**
  2209. * Determine if the size is automatically computed or fixed because manually specified.
  2210. * Use the actualSize property to get the final/real size of the primitive
  2211. * @returns true if the size is automatically computed, false if it were manually specified.
  2212. */
  2213. public get isSizeAuto(): boolean {
  2214. return this._size == null;
  2215. }
  2216. /**
  2217. * Return true if this prim has an auto size which is set by the children's global bounding box
  2218. */
  2219. public get isSizedByContent(): boolean {
  2220. return (this._size == null) && (this._children.length > 0);
  2221. }
  2222. /**
  2223. * Determine if the position is automatically computed or fixed because manually specified.
  2224. * Use the actualPosition property to get the final/real position of the primitive
  2225. * @returns true if the position is automatically computed, false if it were manually specified.
  2226. */
  2227. public get isPositionAuto(): boolean {
  2228. return this._position == null;
  2229. }
  2230. /**
  2231. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  2232. */
  2233. public get pointerEventObservable(): Observable<PrimitivePointerInfo> {
  2234. return this._pointerEventObservable;
  2235. }
  2236. public get zActualOrderChangedObservable(): Observable<number> {
  2237. if (!this._actualZOrderChangedObservable) {
  2238. this._actualZOrderChangedObservable = new Observable<number>();
  2239. }
  2240. return this._actualZOrderChangedObservable;
  2241. }
  2242. public findById(id: string): Prim2DBase {
  2243. if (this._id === id) {
  2244. return this;
  2245. }
  2246. for (let child of this._children) {
  2247. let r = child.findById(id);
  2248. if (r != null) {
  2249. return r;
  2250. }
  2251. }
  2252. }
  2253. protected onZOrderChanged() {
  2254. }
  2255. protected levelIntersect(intersectInfo: IntersectInfo2D): boolean {
  2256. return false;
  2257. }
  2258. /**
  2259. * Capture all the Events of the given PointerId for this primitive.
  2260. * Don't forget to call releasePointerEventsCapture when done.
  2261. * @param pointerId the Id of the pointer to capture the events from.
  2262. */
  2263. public setPointerEventCapture(pointerId: number): boolean {
  2264. return this.owner._setPointerCapture(pointerId, this);
  2265. }
  2266. /**
  2267. * Release a captured pointer made with setPointerEventCapture.
  2268. * @param pointerId the Id of the pointer to release the capture from.
  2269. */
  2270. public releasePointerEventsCapture(pointerId: number): boolean {
  2271. return this.owner._releasePointerCapture(pointerId, this);
  2272. }
  2273. /**
  2274. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  2275. * @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.
  2276. */
  2277. public intersect(intersectInfo: IntersectInfo2D): boolean {
  2278. if (!intersectInfo) {
  2279. return false;
  2280. }
  2281. // If this is null it means this method is call for the first level, initialize stuffs
  2282. let firstLevel = !intersectInfo._globalPickPosition;
  2283. if (firstLevel) {
  2284. // 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).
  2285. intersectInfo._globalPickPosition = Vector2.Zero();
  2286. Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  2287. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  2288. intersectInfo.intersectedPrimitives = new Array<PrimitiveIntersectedInfo>();
  2289. intersectInfo.topMostIntersectedPrimitive = null;
  2290. }
  2291. if (!intersectInfo.intersectHidden && !this.isVisible) {
  2292. return false;
  2293. }
  2294. let id = this.id;
  2295. if (id!=null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  2296. let ownerGroup = this.getExternalData<Group2D>("__cachedGroup__");
  2297. return ownerGroup.intersect(intersectInfo);
  2298. }
  2299. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  2300. let isIntersectionTest = false;
  2301. if (this instanceof Group2D) {
  2302. let g = <Group2D><any>this;
  2303. isIntersectionTest = g.isCachedGroup;
  2304. }
  2305. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  2306. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  2307. intersectInfo._exit(firstLevel);
  2308. return false;
  2309. }
  2310. // Fast rejection test with boundingInfo
  2311. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  2312. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  2313. intersectInfo._exit(firstLevel);
  2314. return false;
  2315. }
  2316. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  2317. let levelIntersectRes = false;
  2318. if (this.isPickable) {
  2319. levelIntersectRes = this.levelIntersect(intersectInfo);
  2320. if (levelIntersectRes) {
  2321. let pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  2322. intersectInfo.intersectedPrimitives.push(pii);
  2323. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  2324. intersectInfo.topMostIntersectedPrimitive = pii;
  2325. }
  2326. // If we must stop at the first intersection, we're done, quit!
  2327. if (intersectInfo.findFirstOnly) {
  2328. intersectInfo._exit(firstLevel);
  2329. return true;
  2330. }
  2331. }
  2332. }
  2333. // Recurse to children if needed
  2334. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  2335. for (let curChild of this._children) {
  2336. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  2337. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  2338. continue;
  2339. }
  2340. // Must compute the localPickLocation for the children level
  2341. Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  2342. // If we got an intersection with the child and we only need to find the first one, quit!
  2343. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  2344. intersectInfo._exit(firstLevel);
  2345. return true;
  2346. }
  2347. }
  2348. }
  2349. intersectInfo._exit(firstLevel);
  2350. return intersectInfo.isIntersected;
  2351. }
  2352. /**
  2353. * Move a child object into a new position regarding its siblings to change its rendering order.
  2354. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  2355. * @param child the object to move
  2356. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  2357. */
  2358. public moveChild(child: Prim2DBase, previous: Prim2DBase): boolean {
  2359. if (child.parent !== this) {
  2360. return false;
  2361. }
  2362. let childIndex = this._children.indexOf(child);
  2363. let prevIndex = previous ? this._children.indexOf(previous) : -1;
  2364. if (!this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder)) {
  2365. this._setFlags(SmartPropertyPrim.flagZOrderDirty);
  2366. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex+1);
  2367. }
  2368. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  2369. return true;
  2370. }
  2371. /**
  2372. * Move the given child so it's displayed on the top of all its siblings
  2373. * @param child the primitive to move to the top
  2374. */
  2375. public moveChildToTop(child: Prim2DBase): boolean {
  2376. return this.moveChild(child, this._children[this._children.length - 1]);
  2377. }
  2378. /**
  2379. * Move the given child so it's displayed on the bottom of all its siblings
  2380. * @param child the primitive to move to the top
  2381. */
  2382. public moveChildToBottom(child: Prim2DBase): boolean {
  2383. return this.moveChild(child, null);
  2384. }
  2385. /**
  2386. * Move this primitive to be at the top among all its sibling
  2387. */
  2388. public moveToTop(): boolean {
  2389. if (this.parent == null) {
  2390. return false;
  2391. }
  2392. return this.parent.moveChildToTop(this);
  2393. }
  2394. /**
  2395. * Move this primitive to be at the bottom among all its sibling
  2396. */
  2397. public moveToBottom() {
  2398. if (this.parent == null) {
  2399. return false;
  2400. }
  2401. return this.parent.moveChildToBottom(this);
  2402. }
  2403. private addChild(child: Prim2DBase) {
  2404. child._parent = this;
  2405. this._boundingBoxDirty();
  2406. let flat = this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder);
  2407. if (flat) {
  2408. child._setFlags(SmartPropertyPrim.flagChildrenFlatZOrder);
  2409. child._setZOrder(this._zOrder, true);
  2410. child._zMax = this._zOrder;
  2411. } else {
  2412. this._setFlags(SmartPropertyPrim.flagZOrderDirty);
  2413. }
  2414. let length = this._children.push(child);
  2415. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  2416. }
  2417. /**
  2418. * Dispose the primitive, remove it from its parent.
  2419. */
  2420. public dispose(): boolean {
  2421. if (!super.dispose()) {
  2422. return false;
  2423. }
  2424. if (this._actionManager) {
  2425. this._actionManager.dispose();
  2426. this._actionManager = null;
  2427. }
  2428. // If there's a parent, remove this object from its parent list
  2429. if (this._parent) {
  2430. if (this instanceof Group2D) {
  2431. let g = <Group2D><any>this;
  2432. if (g.isRenderableGroup) {
  2433. let parentRenderable = <Group2D>this.parent.traverseUp(p => (p instanceof Group2D && p.isRenderableGroup));
  2434. if (parentRenderable != null) {
  2435. let l = parentRenderable._renderableData._childrenRenderableGroups;
  2436. let i = l.indexOf(g);
  2437. if (i !== -1) {
  2438. l.splice(i, 1);
  2439. }
  2440. }
  2441. }
  2442. }
  2443. let i = this._parent._children.indexOf(this);
  2444. if (i !== undefined) {
  2445. this._parent._children.splice(i, 1);
  2446. }
  2447. this._parent = null;
  2448. }
  2449. // Recurse dispose to children
  2450. if (this._children) {
  2451. while (this._children.length > 0) {
  2452. this._children[this._children.length - 1].dispose();
  2453. }
  2454. }
  2455. return true;
  2456. }
  2457. protected onPrimBecomesDirty() {
  2458. if (this._renderGroup && !this._isFlagSet(SmartPropertyPrim.flagPrimInDirtyList)) {
  2459. this._renderGroup._addPrimToDirtyList(this);
  2460. this._setFlags(SmartPropertyPrim.flagPrimInDirtyList);
  2461. }
  2462. }
  2463. public _needPrepare(): boolean {
  2464. return this._areSomeFlagsSet(SmartPropertyPrim.flagVisibilityChanged | SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  2465. }
  2466. public _prepareRender(context: PrepareRender2DContext) {
  2467. this._prepareRenderPre(context);
  2468. this._prepareRenderPost(context);
  2469. }
  2470. public _prepareRenderPre(context: PrepareRender2DContext) {
  2471. }
  2472. public _prepareRenderPost(context: PrepareRender2DContext) {
  2473. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  2474. if (this instanceof Group2D) {
  2475. var self: any = this;
  2476. if (self.isRenderableGroup) {
  2477. return;
  2478. }
  2479. }
  2480. // Check if we need to recurse the prepare to children primitives
  2481. // - must have children
  2482. // - the global transform of this level have changed, or
  2483. // - the visible state of primitive has changed
  2484. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  2485. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  2486. this._children.forEach(c => {
  2487. // As usual stop the recursion if we meet a renderable group
  2488. if (!(c instanceof Group2D && c.isRenderableGroup)) {
  2489. c._prepareRender(context);
  2490. }
  2491. });
  2492. }
  2493. // Finally reset the dirty flags as we've processed everything
  2494. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  2495. this._instanceDirtyFlags = 0;
  2496. }
  2497. protected _canvasPreInit(settings: any) {
  2498. }
  2499. protected static _isCanvasInit: boolean = false;
  2500. protected static CheckParent(parent: Prim2DBase) { // TODO remove
  2501. //if (!Prim2DBase._isCanvasInit && !parent) {
  2502. // 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)");
  2503. //}
  2504. }
  2505. protected updateCachedStatesOf(list: Prim2DBase[], recurse: boolean) {
  2506. for (let cur of list) {
  2507. cur.updateCachedStates(recurse);
  2508. }
  2509. }
  2510. private _parentLayoutDirty() {
  2511. if (!this._parent || this._parent.isDisposed) {
  2512. return;
  2513. }
  2514. this._parent._setLayoutDirty();
  2515. }
  2516. protected _setLayoutDirty() {
  2517. this.onPrimBecomesDirty();
  2518. this._setFlags(SmartPropertyPrim.flagLayoutDirty);
  2519. }
  2520. private _checkPositionChange(): boolean {
  2521. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  2522. console.log(`Can't manually set the position of ${this.id}, the Layout Engine of its parent doesn't allow it`);
  2523. return false;
  2524. }
  2525. return true;
  2526. }
  2527. protected _positioningDirty() {
  2528. this.onPrimBecomesDirty();
  2529. this._setFlags(SmartPropertyPrim.flagPositioningDirty);
  2530. }
  2531. protected _spreadActualOpacityChanged() {
  2532. for (let child of this._children) {
  2533. child._setFlags(SmartPropertyPrim.flagActualOpacityDirty);
  2534. child._updateRenderMode();
  2535. child.onPrimBecomesDirty();
  2536. child._spreadActualOpacityChanged();
  2537. }
  2538. }
  2539. private _changeLayoutEngine(engine: LayoutEngineBase) {
  2540. this._layoutEngine = engine;
  2541. }
  2542. private static _t0: Matrix = new Matrix();
  2543. private static _t1: Matrix = new Matrix();
  2544. private static _t2: Matrix = new Matrix();
  2545. private static _v0: Vector2 = Vector2.Zero(); // Must stay with the value 0,0
  2546. private _updateLocalTransform(): boolean {
  2547. let tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  2548. if (this.checkPropertiesDirty(tflags)) {
  2549. if (this.owner) {
  2550. this.owner.addupdateLocalTransformCounter(1);
  2551. }
  2552. var rot = Quaternion.RotationAxis(new Vector3(0, 0, 1), this._rotation);
  2553. var local: Matrix;
  2554. let pos = this._position ? this.position : this.layoutAreaPos;
  2555. if (this._origin.x === 0 && this._origin.y === 0) {
  2556. local = Matrix.Compose(new Vector3(this._scale.x, this._scale.y, 1), rot, new Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  2557. this._localTransform = local;
  2558. } else {
  2559. // -Origin offset
  2560. let as = this.actualSize;
  2561. Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  2562. // -Origin * rotation
  2563. rot.toRotationMatrix(Prim2DBase._t1);
  2564. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  2565. // -Origin * rotation * scale
  2566. Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  2567. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  2568. // -Origin * rotation * scale * (Origin + Position)
  2569. Matrix.TranslationToRef((as.width * this._origin.x) + pos.x + this._marginOffset.x, (as.height * this._origin.y) + pos.y + this._marginOffset.y, 0, Prim2DBase._t2);
  2570. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  2571. }
  2572. this.clearPropertiesDirty(tflags);
  2573. this._setFlags(SmartPropertyPrim.flagGlobalTransformDirty);
  2574. return true;
  2575. }
  2576. return false;
  2577. }
  2578. private static _transMtx = Matrix.Zero();
  2579. protected updateCachedStates(recurse: boolean) {
  2580. if (this.isDisposed) {
  2581. return;
  2582. }
  2583. this.owner.addCachedGroupRenderCounter(1);
  2584. // Check if the parent is synced
  2585. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(SmartPropertyPrim.flagLayoutDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagZOrderDirty))) {
  2586. this._parent.updateCachedStates(false);
  2587. }
  2588. // Update Z-Order if needed
  2589. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  2590. this._updateZOrder();
  2591. }
  2592. // Update actualSize only if there' not positioning to recompute and the size changed
  2593. // Otherwise positioning will take care of it.
  2594. let sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  2595. if (!this._isFlagSet(SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  2596. let size = this.size;
  2597. if (size) {
  2598. if (this.size.width != null) {
  2599. this.actualSize.width = this.size.width;
  2600. }
  2601. if (this.size.height != null) {
  2602. this.actualSize.height = this.size.height;
  2603. }
  2604. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  2605. }
  2606. }
  2607. let positioningDirty = this._isFlagSet(SmartPropertyPrim.flagPositioningDirty);
  2608. let positioningComputed = positioningDirty && !this._isFlagSet(SmartPropertyPrim.flagPositioningDirty);
  2609. // Check for layout update
  2610. if (this._isFlagSet(SmartPropertyPrim.flagLayoutDirty)) {
  2611. this.owner.addUpdateLayoutCounter(1);
  2612. this._layoutEngine.updateLayout(this);
  2613. this._clearFlags(SmartPropertyPrim.flagLayoutDirty);
  2614. }
  2615. let autoContentChanged = false;
  2616. if (this.isSizeAuto) {
  2617. if (!this._lastAutoSizeArea) {
  2618. autoContentChanged = this.actualSize!==null;
  2619. } else {
  2620. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  2621. }
  2622. }
  2623. // Check for positioning update
  2624. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  2625. this._updatePositioning();
  2626. this._clearFlags(SmartPropertyPrim.flagPositioningDirty);
  2627. if (sizeDirty) {
  2628. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  2629. }
  2630. positioningComputed = true;
  2631. }
  2632. if (positioningComputed && this._parent) {
  2633. this._parentContentArea.copyFrom(this._parent.contentArea);
  2634. }
  2635. // Check if we must update this prim
  2636. if (this === <any>this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  2637. this.owner.addUpdateGlobalTransformCounter(1);
  2638. let curVisibleState = this.isVisible;
  2639. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  2640. // Detect a change of visibility
  2641. this._changeFlags(SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  2642. // Get/compute the localTransform
  2643. let localDirty = this._updateLocalTransform();
  2644. let parentPaddingChanged = false;
  2645. let parentPaddingOffset: Vector2 = Prim2DBase._v0;
  2646. if (this._parent) {
  2647. parentPaddingOffset = this._parent._paddingOffset;
  2648. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  2649. }
  2650. // Check if there are changes in the parent that will force us to update the global matrix
  2651. let parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  2652. // Check if we have to update the globalTransform
  2653. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(SmartPropertyPrim.flagGlobalTransformDirty)) {
  2654. let globalTransform = this._parent ? this._parent._globalTransform : null;
  2655. let localTransform: Matrix;
  2656. Prim2DBase._transMtx.copyFrom(this._localTransform);
  2657. Prim2DBase._transMtx.m[12] += parentPaddingOffset.x;
  2658. Prim2DBase._transMtx.m[13] += parentPaddingOffset.y;
  2659. localTransform = Prim2DBase._transMtx;
  2660. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  2661. this._invGlobalTransform = Matrix.Invert(this._globalTransform);
  2662. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  2663. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  2664. this._clearFlags(SmartPropertyPrim.flagGlobalTransformDirty);
  2665. }
  2666. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  2667. }
  2668. if (recurse) {
  2669. for (let child of this._children) {
  2670. // Stop the recursion if we meet a renderable group
  2671. child.updateCachedStates(!(child instanceof Group2D && child.isRenderableGroup));
  2672. }
  2673. }
  2674. }
  2675. private static _icPos = Vector2.Zero();
  2676. private static _icArea = Size.Zero();
  2677. private static _size = Size.Zero();
  2678. private _updatePositioning() {
  2679. if (this.owner) {
  2680. this.owner.addUpdatePositioningCounter(1);
  2681. }
  2682. // From this point we assume that the primitive layoutArea is computed and up to date.
  2683. // We know have to :
  2684. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  2685. // 2. Determine the contentArea based on the padding property.
  2686. let isSizeAuto = this.isSizeAuto;
  2687. // 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
  2688. if (!this._hasMarginAlignment && (isSizeAuto || (this.actualSize.width == null || this.actualSize.height == null))) {
  2689. if (isSizeAuto || this.actualSize.width == null) {
  2690. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  2691. }
  2692. if (isSizeAuto || this.actualSize.height == null) {
  2693. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  2694. }
  2695. }
  2696. // Apply margin
  2697. if (this._hasMargin) {
  2698. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  2699. this.actualSize = Prim2DBase._size.clone();
  2700. }
  2701. if (this._hasPadding) {
  2702. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  2703. if (isSizeAuto) {
  2704. let content = this.size.clone();
  2705. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  2706. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  2707. this._contentArea.copyFrom(content);
  2708. this.actualSize = Prim2DBase._size.clone();
  2709. // Changing the padding has resize the prim, which forces us to recompute margin again
  2710. if (this._hasMargin) {
  2711. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  2712. }
  2713. } else {
  2714. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  2715. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  2716. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  2717. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  2718. this._paddingOffset.x += Prim2DBase._icPos.x;
  2719. this._paddingOffset.y += Prim2DBase._icPos.y;
  2720. this._contentArea.copyFrom(Prim2DBase._size);
  2721. }
  2722. } else {
  2723. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  2724. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  2725. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  2726. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  2727. this._contentArea.copyFrom(Prim2DBase._icArea);
  2728. }
  2729. if (!this._position) {
  2730. let aPos = new Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  2731. this.actualPosition = aPos;
  2732. }
  2733. if (isSizeAuto) {
  2734. this._lastAutoSizeArea = this.actualSize;
  2735. }
  2736. }
  2737. /**
  2738. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  2739. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  2740. */
  2741. public get contentArea(): Size {
  2742. // Check for positioning update
  2743. if (this._isFlagSet(SmartPropertyPrim.flagPositioningDirty)) {
  2744. this._updatePositioning();
  2745. this._clearFlags(SmartPropertyPrim.flagPositioningDirty);
  2746. }
  2747. return this._contentArea;
  2748. }
  2749. public _patchHierarchy(owner: Canvas2D) {
  2750. this._owner = owner;
  2751. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  2752. if (this._renderGroup != null) {
  2753. return;
  2754. }
  2755. if (this instanceof Group2D) {
  2756. var group: any = this;
  2757. group.detectGroupStates();
  2758. if (group._trackedNode && !group._isFlagSet(SmartPropertyPrim.flagTrackedGroup)) {
  2759. group.owner._registerTrackedNode(this);
  2760. }
  2761. }
  2762. this._renderGroup = <Group2D>this.traverseUp(p => p instanceof Group2D && p.isRenderableGroup);
  2763. if (this._parent) {
  2764. this._parentLayoutDirty();
  2765. }
  2766. // Make sure the prim is in the dirtyList if it should be
  2767. if (this._renderGroup && this.isDirty) {
  2768. let list = this._renderGroup._renderableData._primDirtyList;
  2769. let i = list.indexOf(this);
  2770. if (i === -1) {
  2771. list.push(this);
  2772. }
  2773. }
  2774. // Recurse
  2775. for (let child of this._children) {
  2776. child._hierarchyDepth = this._hierarchyDepth + 1;
  2777. child._patchHierarchy(owner);
  2778. }
  2779. }
  2780. private static _zOrderChangedNotifList = new Array<Prim2DBase>();
  2781. private static _zRebuildReentrency = false;
  2782. private _updateZOrder() {
  2783. let prevLinPos = this._primLinearPosition;
  2784. let startI = 0;
  2785. let startZ = this._zOrder;
  2786. // 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
  2787. let childrenCount = this._children.length;
  2788. if (this._firstZDirtyIndex > 0) {
  2789. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  2790. let prevPrim = this._children[this._firstZDirtyIndex - 1];
  2791. prevLinPos = prevPrim._primLinearPosition;
  2792. startI = this._firstZDirtyIndex - 1;
  2793. startZ = prevPrim._zOrder;
  2794. }
  2795. }
  2796. let startPos = prevLinPos;
  2797. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  2798. Prim2DBase._totalCount = 0;
  2799. for (let i = startI; i < childrenCount; i++) {
  2800. let child = this._children[i];
  2801. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  2802. }
  2803. // Compute the new Z-Order for all the primitives
  2804. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  2805. let zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  2806. // 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.
  2807. if (zDelta < Canvas2D._zMinDelta) {
  2808. // 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...
  2809. if (Prim2DBase._zRebuildReentrency) {
  2810. let p = this._parent;
  2811. if (p == null) {
  2812. // 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...)
  2813. console.log(`Can't compute Z-Order for ${this.id}'s children, zDelta is too small, Z-Order is now in an unstable state`);
  2814. Prim2DBase._zRebuildReentrency = false;
  2815. return;
  2816. }
  2817. p._firstZDirtyIndex = 0;
  2818. return p._updateZOrder();
  2819. }
  2820. Prim2DBase._zRebuildReentrency = true;
  2821. this._firstZDirtyIndex = 0;
  2822. this._updateZOrder();
  2823. Prim2DBase._zRebuildReentrency = false;
  2824. }
  2825. for (let i = startI; i < childrenCount; i++) {
  2826. let child = this._children[i];
  2827. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  2828. }
  2829. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  2830. for (let p of Prim2DBase._zOrderChangedNotifList) {
  2831. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  2832. }
  2833. Prim2DBase._zOrderChangedNotifList.splice(0);
  2834. this._firstZDirtyIndex = Prim2DBase._bigInt;
  2835. this._clearFlags(SmartPropertyPrim.flagZOrderDirty);
  2836. }
  2837. private static _totalCount: number = 0;
  2838. private _updatePrimitiveLinearPosition(prevLinPos: number): number {
  2839. if (this.isManualZOrder) {
  2840. return prevLinPos;
  2841. }
  2842. this._primLinearPosition = ++prevLinPos;
  2843. Prim2DBase._totalCount++;
  2844. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  2845. if (!this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder)) {
  2846. for (let child of this._children) {
  2847. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  2848. }
  2849. }
  2850. return prevLinPos;
  2851. }
  2852. private _updatePrimitiveZOrder(startPos: number, startZ: number, deltaZ: number): number {
  2853. if (this.isManualZOrder) {
  2854. return null;
  2855. }
  2856. let newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  2857. let isFlat = this._isFlagSet(SmartPropertyPrim.flagChildrenFlatZOrder);
  2858. this._setZOrder(newZ, false);
  2859. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  2860. this._firstZDirtyIndex = Prim2DBase._bigInt;
  2861. this._clearFlags(SmartPropertyPrim.flagZOrderDirty);
  2862. }
  2863. let curZ: number = newZ;
  2864. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  2865. if (isFlat) {
  2866. if (this._children.length > 0) {
  2867. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  2868. for (let child of this._children) {
  2869. child._updatePrimitiveFlatZOrder(this._zOrder);
  2870. }
  2871. }
  2872. } else {
  2873. for (let child of this._children) {
  2874. let r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  2875. if (r != null) {
  2876. curZ = r;
  2877. }
  2878. }
  2879. }
  2880. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  2881. return curZ;
  2882. }
  2883. private _updatePrimitiveFlatZOrder(newZ: number) {
  2884. if (this.isManualZOrder) {
  2885. return;
  2886. }
  2887. this._setZOrder(newZ, false);
  2888. this._zMax = newZ;
  2889. if (this._isFlagSet(SmartPropertyPrim.flagZOrderDirty)) {
  2890. this._firstZDirtyIndex = Prim2DBase._bigInt;
  2891. this._clearFlags(SmartPropertyPrim.flagZOrderDirty);
  2892. }
  2893. for (let child of this._children) {
  2894. child._updatePrimitiveFlatZOrder(newZ);
  2895. }
  2896. }
  2897. private _setZOrder(newZ: number, directEmit: boolean) {
  2898. if (newZ !== this._zOrder) {
  2899. this._zOrder = newZ;
  2900. this.onPrimBecomesDirty();
  2901. this.onZOrderChanged();
  2902. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  2903. if (directEmit) {
  2904. this._actualZOrderChangedObservable.notifyObservers(newZ);
  2905. } else {
  2906. Prim2DBase._zOrderChangedNotifList.push(this);
  2907. }
  2908. }
  2909. }
  2910. }
  2911. protected _updateRenderMode() {
  2912. }
  2913. /**
  2914. * This method is used to alter the contentArea of the Primitive before margin is applied.
  2915. * 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.
  2916. * @param primSize the current size of the primitive
  2917. * @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!
  2918. * @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!
  2919. */
  2920. protected _getInitialContentAreaToRef(primSize: Size, initialContentPosition: Vector2, initialContentArea: Size) {
  2921. initialContentArea.copyFrom(primSize);
  2922. initialContentPosition.x = initialContentPosition.y = 0;
  2923. }
  2924. /**
  2925. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  2926. * Check the Rectangle2D implementation for a concrete application.
  2927. * @param primSize the current size of the primitive
  2928. * @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!
  2929. */
  2930. protected _getActualSizeFromContentToRef(primSize: Size, newPrimSize: Size) {
  2931. newPrimSize.copyFrom(primSize);
  2932. }
  2933. private _owner: Canvas2D;
  2934. private _parent: Prim2DBase;
  2935. private _actionManager: ActionManager;
  2936. protected _children: Array<Prim2DBase>;
  2937. private _renderGroup: Group2D;
  2938. protected _hierarchyDepth: number;
  2939. protected _zOrder: number;
  2940. private _manualZOrder: number;
  2941. protected _zMax: number;
  2942. private _firstZDirtyIndex: number;
  2943. private _primLinearPosition: number;
  2944. private _margin: PrimitiveThickness;
  2945. private _padding: PrimitiveThickness;
  2946. private _marginAlignment: PrimitiveAlignment;
  2947. public _pointerEventObservable: Observable<PrimitivePointerInfo>;
  2948. private _actualZOrderChangedObservable: Observable<number>;
  2949. private _id: string;
  2950. private _position: Vector2;
  2951. private _actualPosition: Vector2;
  2952. protected _size: Size;
  2953. protected _actualSize: Size;
  2954. public _boundingSize: Size;
  2955. protected _minSize: Size;
  2956. protected _maxSize: Size;
  2957. protected _desiredSize: Size;
  2958. private _layoutEngine: LayoutEngineBase;
  2959. private _marginOffset: Vector2;
  2960. private _paddingOffset: Vector2;
  2961. private _parentPaddingOffset: Vector2;
  2962. private _parentContentArea: Size;
  2963. private _lastAutoSizeArea: Size;
  2964. private _layoutAreaPos: Vector2;
  2965. private _layoutArea: Size;
  2966. private _contentArea: Size;
  2967. private _rotation: number;
  2968. private _scale: Vector2;
  2969. private _origin: Vector2;
  2970. protected _opacity: number;
  2971. private _actualOpacity: number;
  2972. private _actualScale : Vector2;
  2973. // Stores the step of the parent for which the current global transform was computed
  2974. // If the parent has a new step, it means this prim's global transform must be updated
  2975. protected _parentTransformStep: number;
  2976. // Stores the step corresponding of the global transform for this prim
  2977. // If a child prim has an older _parentTransformStep it means the child's transform should be updated
  2978. protected _globalTransformStep: number;
  2979. // Stores the previous
  2980. protected _globalTransformProcessStep: number;
  2981. protected _localTransform: Matrix;
  2982. protected _globalTransform: Matrix;
  2983. protected _invGlobalTransform: Matrix;
  2984. }
  2985. }