babylon.canvas2d.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5. };
  6. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  10. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11. };
  12. var BABYLON;
  13. (function (BABYLON) {
  14. // This class contains data that lifetime is bounding to the Babylon Engine object
  15. var Canvas2DEngineBoundData = (function () {
  16. function Canvas2DEngineBoundData() {
  17. this._modelCache = new BABYLON.StringDictionary();
  18. }
  19. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  20. return this._modelCache.getOrAddWithFactory(key, factory);
  21. };
  22. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  23. if (!modelRenderCache.isDisposed) {
  24. return false;
  25. }
  26. this._modelCache.remove(modelRenderCache.modelKey);
  27. return true;
  28. };
  29. return Canvas2DEngineBoundData;
  30. })();
  31. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  32. var Canvas2D = (function (_super) {
  33. __extends(Canvas2D, _super);
  34. function Canvas2D(scene, settings) {
  35. var _this = this;
  36. _super.call(this, settings);
  37. /**
  38. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  39. * Beware that you have to take under consideration the origin and the renderScaleFactor in your calculations! Good luck!
  40. */
  41. this.worldSpaceToNodeLocal = function (worldPos) {
  42. var node = _this._worldSpaceNode;
  43. if (!node) {
  44. return;
  45. }
  46. var mtx = node.getWorldMatrix().clone();
  47. mtx.invert();
  48. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  49. var rsf = _this._renderScaleFactor;
  50. var res = new BABYLON.Vector2(v.x * rsf, v.y * rsf);
  51. var size = _this.actualSize;
  52. var o = _this.origin;
  53. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  54. res.y += size.width * 0.5;
  55. return res;
  56. };
  57. this._notifDebugMode = false;
  58. this._mapCounter = 0;
  59. BABYLON.Prim2DBase._isCanvasInit = false;
  60. if (!settings) {
  61. settings = {};
  62. }
  63. var renderScaleFactor = (settings.renderScaleFactor == null) ? 1 : settings.renderScaleFactor;
  64. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  65. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  66. this._background.zOrder = 1.0;
  67. this._background.isPickable = false;
  68. this._background.origin = BABYLON.Vector2.Zero();
  69. this._background.levelVisible = false;
  70. if (settings.backgroundRoundRadius != null) {
  71. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  72. }
  73. if (settings.backgroundBorder != null) {
  74. if (typeof (settings.backgroundBorder) === "string") {
  75. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  76. }
  77. else {
  78. this.backgroundBorder = settings.backgroundBorder;
  79. }
  80. }
  81. if (settings.backgroundBorderThickNess != null) {
  82. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  83. }
  84. if (settings.backgroundFill != null) {
  85. if (typeof (settings.backgroundFill) === "string") {
  86. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  87. }
  88. else {
  89. this.backgroundFill = settings.backgroundFill;
  90. }
  91. }
  92. this._background._patchHierarchy(this);
  93. }
  94. var engine = scene.getEngine();
  95. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  96. this._renderScaleFactor = renderScaleFactor;
  97. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  98. this._capturedPointers = new BABYLON.StringDictionary();
  99. this._pickStartingPosition = BABYLON.Vector2.Zero();
  100. this._hierarchyLevelMaxSiblingCount = 50;
  101. this._hierarchyDepthOffset = 0;
  102. this._siblingDepthOffset = 1 / this._hierarchyLevelMaxSiblingCount;
  103. this._scene = scene;
  104. this._engine = engine;
  105. this._renderingSize = new BABYLON.Size(0, 0);
  106. this._trackedGroups = new Array();
  107. this._patchHierarchy(this);
  108. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  109. this._fitRenderingDevice = !settings.size;
  110. if (!settings.size) {
  111. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  112. }
  113. else {
  114. settings.size.height *= renderScaleFactor;
  115. settings.size.width *= renderScaleFactor;
  116. }
  117. // Register scene dispose to also dispose the canvas when it'll happens
  118. scene.onDisposeObservable.add(function (d, s) {
  119. _this.dispose();
  120. });
  121. if (this._isScreenSpace) {
  122. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  123. _this._engine.clear(null, false, true);
  124. _this._render();
  125. });
  126. }
  127. else {
  128. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  129. _this._render();
  130. });
  131. }
  132. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  133. // this._supprtInstancedArray = false; // TODO REMOVE!!!
  134. this._setupInteraction(enableInteraction);
  135. }
  136. Canvas2D.prototype._canvasPreInit = function (settings) {
  137. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  138. this._cachingStrategy = cachingStrategy;
  139. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  140. };
  141. Canvas2D.prototype._setupInteraction = function (enable) {
  142. var _this = this;
  143. // No change detection
  144. if (enable === this._interactionEnabled) {
  145. return;
  146. }
  147. // Set the new state
  148. this._interactionEnabled = enable;
  149. // ScreenSpace mode
  150. if (this._isScreenSpace) {
  151. // Disable interaction
  152. if (!enable) {
  153. if (this._scenePrePointerObserver) {
  154. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  155. this._scenePrePointerObserver = null;
  156. }
  157. return;
  158. }
  159. // Enable Interaction
  160. // Register the observable
  161. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  162. var hs = 1 / _this.engine.getHardwareScalingLevel();
  163. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  164. _this._handlePointerEventForInteraction(e, localPos, s);
  165. });
  166. }
  167. else {
  168. var scene = this.scene;
  169. if (enable) {
  170. scene.constantlyUpdateMeshUnderPointer = true;
  171. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  172. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  173. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  174. _this._handlePointerEventForInteraction(e, localPos, s);
  175. }
  176. });
  177. }
  178. else {
  179. if (this._scenePointerObserver) {
  180. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  181. this._scenePointerObserver = null;
  182. }
  183. }
  184. }
  185. };
  186. /**
  187. * Internal method, you should use the Prim2DBase version instead
  188. */
  189. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  190. if (this.isPointerCaptured(pointerId)) {
  191. return false;
  192. }
  193. // Try to capture the pointer on the HTML side
  194. try {
  195. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  196. }
  197. catch (e) {
  198. }
  199. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  200. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  201. this._capturedPointers.add(pointerId.toString(), primitive);
  202. return true;
  203. };
  204. /**
  205. * Internal method, you should use the Prim2DBase version instead
  206. */
  207. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  208. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  209. return false;
  210. }
  211. // Try to release the pointer on the HTML side
  212. try {
  213. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  214. }
  215. catch (e) {
  216. }
  217. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  218. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  219. this._capturedPointers.remove(pointerId.toString());
  220. return true;
  221. };
  222. /**
  223. * Determine if the given pointer is captured or not
  224. * @param pointerId the Id of the pointer
  225. * @return true if it's captured, false otherwise
  226. */
  227. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  228. return this._capturedPointers.contains(pointerId.toString());
  229. };
  230. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  231. // Avoid unnecessary lookup
  232. if (this._capturedPointers.count === 0) {
  233. return null;
  234. }
  235. return this._capturedPointers.get(pointerId.toString());
  236. };
  237. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  238. // Dispose check
  239. if (this.isDisposed) {
  240. return;
  241. }
  242. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  243. this._updatePointerInfo(eventData, localPosition);
  244. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  245. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  246. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  247. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  248. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  249. this._updateOverStatus();
  250. // Check if we have nothing to raise
  251. if (!this._actualOverPrimitive && !capturedPrim) {
  252. return;
  253. }
  254. // Update the relatedTarget info with the over primitive or the captured one (if any)
  255. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  256. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  257. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  258. // Analyze the pointer event type and fire proper events on the primitive
  259. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  260. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  261. }
  262. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  263. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  264. }
  265. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  266. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  267. }
  268. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  269. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  270. }
  271. };
  272. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  273. var pii = this._primPointerInfo;
  274. if (!pii.canvasPointerPos) {
  275. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  276. }
  277. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  278. var engine = this._scene.getEngine();
  279. if (this._isScreenSpace) {
  280. var cameraViewport = camera.viewport;
  281. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  282. // Moving coordinates to local viewport world
  283. var x = localPosition.x - viewport.x;
  284. var y = localPosition.y - viewport.y;
  285. pii.canvasPointerPos.x = x - this.actualPosition.x;
  286. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  287. }
  288. else {
  289. pii.canvasPointerPos.x = localPosition.x;
  290. pii.canvasPointerPos.y = localPosition.y;
  291. }
  292. pii.mouseWheelDelta = 0;
  293. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  294. var event = eventData.event;
  295. if (event.wheelDelta) {
  296. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  297. }
  298. else if (event.detail) {
  299. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  300. }
  301. }
  302. else {
  303. var pe = eventData.event;
  304. pii.ctrlKey = pe.ctrlKey;
  305. pii.altKey = pe.altKey;
  306. pii.shiftKey = pe.shiftKey;
  307. pii.metaKey = pe.metaKey;
  308. pii.button = pe.button;
  309. pii.buttons = pe.buttons;
  310. pii.pointerId = pe.pointerId;
  311. pii.width = pe.width;
  312. pii.height = pe.height;
  313. pii.presssure = pe.pressure;
  314. pii.tilt.x = pe.tiltX;
  315. pii.tilt.y = pe.tiltY;
  316. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  317. }
  318. };
  319. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  320. if (this.scene.getRenderId() === this._intersectionRenderId) {
  321. return;
  322. }
  323. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  324. if (!this._globalTransform) {
  325. this.updateCachedStates(true);
  326. }
  327. var ii = Canvas2D._interInfo;
  328. ii.pickPosition.x = mouseLocalPos.x;
  329. ii.pickPosition.y = mouseLocalPos.y;
  330. ii.findFirstOnly = false;
  331. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  332. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  333. this._previousIntersectionList = this._actualIntersectionList;
  334. this._actualIntersectionList = null;
  335. this._previousOverPrimitive = this._actualOverPrimitive;
  336. this._actualOverPrimitive = null;
  337. return;
  338. }
  339. this.intersect(ii);
  340. this._previousIntersectionList = this._actualIntersectionList;
  341. this._actualIntersectionList = ii.intersectedPrimitives;
  342. this._previousOverPrimitive = this._actualOverPrimitive;
  343. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  344. this._intersectionRenderId = this.scene.getRenderId();
  345. };
  346. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  347. Canvas2D.prototype._updateOverStatus = function () {
  348. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  349. return;
  350. }
  351. // Detect a change of over
  352. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  353. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  354. if (prevPrim !== actualPrim) {
  355. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  356. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  357. // Notify the previous "over" prim that the pointer is no longer over it
  358. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  359. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  360. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  361. }
  362. // Notify the new "over" prim that the pointer is over it
  363. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  364. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  365. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  366. }
  367. }
  368. this._hoverStatusRenderId = this.scene.getRenderId();
  369. };
  370. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  371. if (this._primPointerInfo.isCaptured) {
  372. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  373. }
  374. else {
  375. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  376. var pii = _a[_i];
  377. if (pii.prim === prim) {
  378. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  379. return;
  380. }
  381. }
  382. }
  383. };
  384. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  385. if (!this._notifDebugMode) {
  386. return;
  387. }
  388. var debug = "";
  389. for (var i = 0; i < prim.hierarchyDepth; i++) {
  390. debug += " ";
  391. }
  392. var pii = this._primPointerInfo;
  393. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  394. console.log(debug);
  395. };
  396. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  397. var ppi = this._primPointerInfo;
  398. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  399. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  400. this._notifParents(prim, mask);
  401. }
  402. var bubbleCancelled = false;
  403. var cur = prim;
  404. while (cur) {
  405. // Only trigger the observers if the primitive is intersected (except for out)
  406. if (!bubbleCancelled) {
  407. this._updatePrimPointerPos(cur);
  408. // Exec the observers
  409. this._debugExecObserver(cur, mask);
  410. cur._pointerEventObservable.notifyObservers(ppi, mask);
  411. this._triggerActionManager(cur, ppi, mask, eventData);
  412. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  413. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  414. if (ppi.cancelBubble) {
  415. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  416. return;
  417. }
  418. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  419. bubbleCancelled = true;
  420. }
  421. }
  422. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  423. if (bubbleCancelled) {
  424. this._updatePrimPointerPos(cur);
  425. }
  426. // Trigger a PointerEnter corresponding to the PointerOver
  427. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  428. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  429. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  430. }
  431. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  432. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  433. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  434. }
  435. // Loop to the parent
  436. cur = cur.parent;
  437. }
  438. };
  439. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  440. var _this = this;
  441. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  442. if (!this._globalTransform) {
  443. this.updateCachedStates(true);
  444. }
  445. // Process Trigger related to PointerDown
  446. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  447. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  448. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  449. this._pickStartingTime = new Date().getTime();
  450. this._pickedDownPrim = null;
  451. if (prim.actionManager) {
  452. this._pickedDownPrim = prim;
  453. if (prim.actionManager.hasPickTriggers) {
  454. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  455. switch (eventData.button) {
  456. case 0:
  457. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  458. break;
  459. case 1:
  460. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  461. break;
  462. case 2:
  463. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  464. break;
  465. }
  466. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  467. }
  468. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  469. window.setTimeout(function () {
  470. var ppi = _this._primPointerInfo;
  471. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  472. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  473. var ii = new BABYLON.IntersectInfo2D();
  474. ii.pickPosition = ppi.canvasPointerPos.clone();
  475. ii.findFirstOnly = false;
  476. _this.intersect(ii);
  477. if (ii.isPrimIntersected(prim) !== null) {
  478. if (prim.actionManager) {
  479. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  480. _this._pickStartingTime = 0;
  481. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  482. }
  483. }
  484. }
  485. }, BABYLON.ActionManager.LongPressDelay);
  486. }
  487. }
  488. }
  489. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  490. this._pickStartingTime = 0;
  491. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  492. if (prim.actionManager) {
  493. // OnPickUpTrigger
  494. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  495. // OnPickTrigger
  496. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  497. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  498. }
  499. }
  500. // OnPickOutTrigger
  501. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  502. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  503. }
  504. }
  505. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  506. if (prim.actionManager) {
  507. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  508. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  509. }
  510. }
  511. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  512. if (prim.actionManager) {
  513. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  514. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  515. }
  516. }
  517. };
  518. Canvas2D.prototype._notifParents = function (prim, mask) {
  519. var pii = this._primPointerInfo;
  520. var curPrim = this;
  521. while (curPrim) {
  522. this._updatePrimPointerPos(curPrim);
  523. // Fire the proper notification
  524. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  525. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  526. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  527. }
  528. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  529. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  530. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  531. }
  532. curPrim = curPrim.parent;
  533. }
  534. };
  535. /**
  536. * Don't forget to call the dispose method when you're done with the Canvas instance.
  537. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  538. */
  539. Canvas2D.prototype.dispose = function () {
  540. if (!_super.prototype.dispose.call(this)) {
  541. return false;
  542. }
  543. if (this.interactionEnabled) {
  544. this._setupInteraction(false);
  545. }
  546. if (this._beforeRenderObserver) {
  547. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  548. this._beforeRenderObserver = null;
  549. }
  550. if (this._afterRenderObserver) {
  551. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  552. this._afterRenderObserver = null;
  553. }
  554. if (this._groupCacheMaps) {
  555. this._groupCacheMaps.forEach(function (m) { return m.dispose(); });
  556. this._groupCacheMaps = null;
  557. }
  558. };
  559. Object.defineProperty(Canvas2D.prototype, "scene", {
  560. /**
  561. * Accessor to the Scene that owns the Canvas
  562. * @returns The instance of the Scene object
  563. */
  564. get: function () {
  565. return this._scene;
  566. },
  567. enumerable: true,
  568. configurable: true
  569. });
  570. Object.defineProperty(Canvas2D.prototype, "engine", {
  571. /**
  572. * Accessor to the Engine that drives the Scene used by this Canvas
  573. * @returns The instance of the Engine object
  574. */
  575. get: function () {
  576. return this._engine;
  577. },
  578. enumerable: true,
  579. configurable: true
  580. });
  581. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  582. /**
  583. * Accessor of the Caching Strategy used by this Canvas.
  584. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  585. * @returns the value corresponding to the used strategy.
  586. */
  587. get: function () {
  588. return this._cachingStrategy;
  589. },
  590. enumerable: true,
  591. configurable: true
  592. });
  593. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  594. /**
  595. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  596. */
  597. get: function () {
  598. return this._worldSpaceNode;
  599. },
  600. set: function (val) {
  601. this._worldSpaceNode = val;
  602. },
  603. enumerable: true,
  604. configurable: true
  605. });
  606. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  607. /**
  608. * Check if the WebGL Instanced Array extension is supported or not
  609. */
  610. get: function () {
  611. return this._supprtInstancedArray;
  612. },
  613. enumerable: true,
  614. configurable: true
  615. });
  616. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  617. /**
  618. * Property that defines the fill object used to draw the background of the Canvas.
  619. * Note that Canvas with a Caching Strategy of
  620. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  621. */
  622. get: function () {
  623. if (!this._background || !this._background.isVisible) {
  624. return null;
  625. }
  626. return this._background.fill;
  627. },
  628. set: function (value) {
  629. this.checkBackgroundAvailability();
  630. if (value === this._background.fill) {
  631. return;
  632. }
  633. this._background.fill = value;
  634. this._background.levelVisible = true;
  635. },
  636. enumerable: true,
  637. configurable: true
  638. });
  639. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  640. /**
  641. * Property that defines the border object used to draw the background of the Canvas.
  642. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  643. */
  644. get: function () {
  645. if (!this._background || !this._background.isVisible) {
  646. return null;
  647. }
  648. return this._background.border;
  649. },
  650. set: function (value) {
  651. this.checkBackgroundAvailability();
  652. if (value === this._background.border) {
  653. return;
  654. }
  655. this._background.border = value;
  656. this._background.levelVisible = true;
  657. },
  658. enumerable: true,
  659. configurable: true
  660. });
  661. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  662. /**
  663. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  664. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  665. */
  666. get: function () {
  667. if (!this._background || !this._background.isVisible) {
  668. return null;
  669. }
  670. return this._background.borderThickness;
  671. },
  672. set: function (value) {
  673. this.checkBackgroundAvailability();
  674. if (value === this._background.borderThickness) {
  675. return;
  676. }
  677. this._background.borderThickness = value;
  678. },
  679. enumerable: true,
  680. configurable: true
  681. });
  682. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  683. /**
  684. * You can set the roundRadius of the background
  685. * @returns The current roundRadius
  686. */
  687. get: function () {
  688. if (!this._background || !this._background.isVisible) {
  689. return null;
  690. }
  691. return this._background.roundRadius;
  692. },
  693. set: function (value) {
  694. this.checkBackgroundAvailability();
  695. if (value === this._background.roundRadius) {
  696. return;
  697. }
  698. this._background.roundRadius = value;
  699. this._background.levelVisible = true;
  700. },
  701. enumerable: true,
  702. configurable: true
  703. });
  704. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  705. /**
  706. * Enable/Disable interaction for this Canvas
  707. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  708. */
  709. get: function () {
  710. return this._interactionEnabled;
  711. },
  712. set: function (enable) {
  713. this._setupInteraction(enable);
  714. },
  715. enumerable: true,
  716. configurable: true
  717. });
  718. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  719. /**
  720. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  721. * @returns {}
  722. */
  723. get: function () {
  724. return this.__engineData;
  725. },
  726. enumerable: true,
  727. configurable: true
  728. });
  729. Canvas2D.prototype.checkBackgroundAvailability = function () {
  730. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  731. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  732. }
  733. };
  734. Canvas2D.prototype.onPrimBecomesDirty = function () {
  735. this._addPrimToDirtyList(this);
  736. };
  737. Canvas2D.prototype._updateTrackedNodes = function () {
  738. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  739. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  740. var rh = this.engine.getRenderHeight();
  741. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  742. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  743. var group = _a[_i];
  744. if (group.isDisposed || !group.isVisible) {
  745. continue;
  746. }
  747. var node = group.trackedNode;
  748. var worldMtx = node.getWorldMatrix();
  749. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  750. group.x = Math.round(proj.x);
  751. group.y = Math.round(rh - proj.y);
  752. }
  753. };
  754. Canvas2D.prototype._updateCanvasState = function () {
  755. // Check if the update has already been made for this render Frame
  756. if (this.scene.getRenderId() === this._updateRenderId) {
  757. return;
  758. }
  759. // Detect a change of rendering size
  760. var renderingSizeChanged = false;
  761. var newWidth = this.engine.getRenderWidth();
  762. if (newWidth !== this._renderingSize.width) {
  763. renderingSizeChanged = true;
  764. }
  765. this._renderingSize.width = newWidth;
  766. var newHeight = this.engine.getRenderHeight();
  767. if (newHeight !== this._renderingSize.height) {
  768. renderingSizeChanged = true;
  769. }
  770. this._renderingSize.height = newHeight;
  771. // If the canvas fit the rendering size and it changed, update
  772. if (renderingSizeChanged && this._fitRenderingDevice) {
  773. this.size = this._renderingSize;
  774. if (this._background) {
  775. this._background.size = this.size;
  776. }
  777. // Dirty the Layout at the Canvas level to recompute as the size changed
  778. this._setLayoutDirty();
  779. }
  780. var context = new BABYLON.PrepareRender2DContext();
  781. ++this._globalTransformProcessStep;
  782. this.updateCachedStates(false);
  783. this._prepareGroupRender(context);
  784. this._updateRenderId = this.scene.getRenderId();
  785. };
  786. /**
  787. * Method that renders the Canvas, you should not invoke
  788. */
  789. Canvas2D.prototype._render = function () {
  790. this._updateTrackedNodes();
  791. this._updateCanvasState();
  792. if (this._primPointerInfo.canvasPointerPos) {
  793. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  794. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  795. }
  796. this.engine.setState(false);
  797. this._groupRender();
  798. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  799. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  800. this._cachedCanvasGroup._renderCachedCanvas();
  801. }
  802. };
  803. /**
  804. * Internal method that allocate a cache for the given group.
  805. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  806. * @param group The group to allocate the cache of.
  807. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  808. */
  809. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize) {
  810. // Determine size
  811. var size = group.actualSize;
  812. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  813. if (minSize) {
  814. size.width = Math.max(minSize.width, size.width);
  815. size.height = Math.max(minSize.height, size.height);
  816. }
  817. if (!this._groupCacheMaps) {
  818. this._groupCacheMaps = new Array();
  819. }
  820. // Try to find a spot in one of the cached texture
  821. var res = null;
  822. for (var _i = 0, _a = this._groupCacheMaps; _i < _a.length; _i++) {
  823. var map = _a[_i];
  824. var node = map.allocateRect(size);
  825. if (node) {
  826. res = { node: node, texture: map };
  827. break;
  828. }
  829. }
  830. // Couldn't find a map that could fit the rect, create a new map for it
  831. if (!res) {
  832. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  833. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  834. if (size.width > mapSize.width || size.height > mapSize.height) {
  835. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  836. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  837. }
  838. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  839. map = new BABYLON.MapTexture(id, this._scene, mapSize);
  840. this._groupCacheMaps.push(map);
  841. var node = map.allocateRect(size);
  842. res = { node: node, texture: map };
  843. }
  844. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  845. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  846. if (group !== this || this._isScreenSpace) {
  847. var node = res.node;
  848. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  849. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  850. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  851. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  852. sprite.zOrder = 1;
  853. sprite.origin = BABYLON.Vector2.Zero();
  854. }
  855. else {
  856. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  857. sprite.origin = group.origin.clone();
  858. res.sprite = sprite;
  859. }
  860. }
  861. return res;
  862. };
  863. /**
  864. * Internal method used to register a Scene Node to track position for the given group
  865. * Do not invoke this method, for internal purpose only.
  866. * @param group the group to track its associated Scene Node
  867. */
  868. Canvas2D.prototype._registerTrackedNode = function (group) {
  869. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  870. return;
  871. }
  872. this._trackedGroups.push(group);
  873. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  874. };
  875. /**
  876. * Internal method used to unregister a tracked Scene Node
  877. * Do not invoke this method, it's for internal purpose only.
  878. * @param group the group to unregister its tracked Scene Node from.
  879. */
  880. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  881. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  882. return;
  883. }
  884. var i = this._trackedGroups.indexOf(group);
  885. if (i !== -1) {
  886. this._trackedGroups.splice(i, 1);
  887. }
  888. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  889. };
  890. /**
  891. * Get a Solid Color Brush instance matching the given color.
  892. * @param color The color to retrieve
  893. * @return A shared instance of the SolidColorBrush2D class that use the given color
  894. */
  895. Canvas2D.GetSolidColorBrush = function (color) {
  896. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  897. };
  898. /**
  899. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  900. * @param color The color to retrieve
  901. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  902. */
  903. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  904. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  905. };
  906. /**
  907. * Get a Gradient Color Brush
  908. * @param color1 starting color
  909. * @param color2 engine color
  910. * @param translation translation vector to apply. default is [0;0]
  911. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  912. * @param scale scaling factor to apply. default is 1.
  913. */
  914. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  915. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  916. if (rotation === void 0) { rotation = 0; }
  917. if (scale === void 0) { scale = 1; }
  918. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  919. };
  920. /**
  921. * Create a solid or gradient brush from a string value.
  922. * @param brushString should be either
  923. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  924. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  925. */
  926. Canvas2D.GetBrushFromString = function (brushString) {
  927. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  928. brushString = brushString.trim();
  929. var split = brushString.split(",");
  930. // Solid, formatted as: "[solid:]#FF808080"
  931. if (split.length === 1) {
  932. var value = null;
  933. if (brushString.indexOf("solid:") === 0) {
  934. value = brushString.substr(6).trim();
  935. }
  936. else if (brushString.indexOf("#") === 0) {
  937. value = brushString;
  938. }
  939. else {
  940. return null;
  941. }
  942. return Canvas2D.GetSolidColorBrushFromHex(value);
  943. }
  944. else {
  945. if (split[0].indexOf("gradient:") === 0) {
  946. split[0] = split[0].substr(9).trim();
  947. }
  948. try {
  949. var start = BABYLON.Color4.FromHexString(split[0].trim());
  950. var end = BABYLON.Color4.FromHexString(split[1].trim());
  951. var t = BABYLON.Vector2.Zero();
  952. if (split.length > 2) {
  953. var v = split[2].trim();
  954. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  955. return null;
  956. }
  957. var sep = v.indexOf(":");
  958. var x = parseFloat(v.substr(1, sep));
  959. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  960. t = new BABYLON.Vector2(x, y);
  961. }
  962. var r = 0;
  963. if (split.length > 3) {
  964. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  965. }
  966. var s = 1;
  967. if (split.length > 4) {
  968. s = parseFloat(split[4].trim());
  969. }
  970. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  971. }
  972. catch (e) {
  973. return null;
  974. }
  975. }
  976. };
  977. /**
  978. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  979. * This strategy doesn't allow primitives added directly as children of the Canvas.
  980. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  981. */
  982. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  983. /**
  984. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  985. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  986. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  987. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  988. */
  989. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  990. /**
  991. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  992. */
  993. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  994. /**
  995. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  996. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  997. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  998. */
  999. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  1000. Canvas2D.hierarchyLevelMaxSiblingCount = 50;
  1001. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  1002. Canvas2D._v = BABYLON.Vector3.Zero();
  1003. Canvas2D._m = BABYLON.Matrix.Identity();
  1004. /**
  1005. * Define the default size used for both the width and height of a MapTexture to allocate.
  1006. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  1007. */
  1008. Canvas2D._groupTextureCacheSize = 1024;
  1009. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  1010. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  1011. Canvas2D = __decorate([
  1012. BABYLON.className("Canvas2D")
  1013. ], Canvas2D);
  1014. return Canvas2D;
  1015. })(BABYLON.Group2D);
  1016. BABYLON.Canvas2D = Canvas2D;
  1017. var WorldSpaceCanvas2D = (function (_super) {
  1018. __extends(WorldSpaceCanvas2D, _super);
  1019. /**
  1020. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  1021. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  1022. * @param scene the Scene that owns the Canvas
  1023. * @param size the dimension of the Canvas in World Space
  1024. * @param settings a combination of settings, possible ones are
  1025. * - children: an array of direct children primitives
  1026. * - id: a text identifier, for information purpose only, default is null.
  1027. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  1028. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  1029. * - renderScaleFactor A scale factor applied to create the rendering texture that will be mapped in the Scene Rectangle. If you set 2 for instance the texture will be twice large in width and height. A greater value will allow to achieve a better rendering quality. Default value is 1.
  1030. * BE AWARE that the Canvas true dimension will be size*renderScaleFactor, then all coordinates and size will have to be express regarding this size.
  1031. * TIPS: if you want a renderScaleFactor independent reference of frame, create a child Group2D in the Canvas with position 0,0 and size set to null, then set its scale property to the same amount than the renderScaleFactor, put all your primitive inside using coordinates regarding the size property you pick for the Canvas and you'll be fine.
  1032. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  1033. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  1034. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  1035. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  1036. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  1037. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1038. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1039. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  1040. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  1041. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1042. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1043. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1044. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  1045. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  1046. */
  1047. function WorldSpaceCanvas2D(scene, size, settings) {
  1048. BABYLON.Prim2DBase._isCanvasInit = true;
  1049. var s = settings;
  1050. s.isScreenSpace = false;
  1051. s.size = size.clone();
  1052. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  1053. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  1054. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  1055. }
  1056. _super.call(this, scene, settings);
  1057. BABYLON.Prim2DBase._isCanvasInit = false;
  1058. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  1059. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  1060. //}
  1061. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  1062. var id = settings ? settings.id || null : null;
  1063. if (createWorldSpaceNode) {
  1064. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  1065. var vertexData = BABYLON.VertexData.CreatePlane({
  1066. width: size.width,
  1067. height: size.height,
  1068. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  1069. });
  1070. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  1071. this.applyCachedTexture(vertexData, mtl);
  1072. vertexData.applyToMesh(plane, false);
  1073. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  1074. mtl.disableLighting = true;
  1075. mtl.useAlphaFromDiffuseTexture = true;
  1076. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  1077. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  1078. plane.material = mtl;
  1079. this._worldSpaceNode = plane;
  1080. }
  1081. else {
  1082. this._worldSpaceNode = settings.customWorldSpaceNode;
  1083. this.applyCachedTexture(null, null);
  1084. }
  1085. }
  1086. WorldSpaceCanvas2D = __decorate([
  1087. BABYLON.className("WorldSpaceCanvas2D")
  1088. ], WorldSpaceCanvas2D);
  1089. return WorldSpaceCanvas2D;
  1090. })(Canvas2D);
  1091. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  1092. var ScreenSpaceCanvas2D = (function (_super) {
  1093. __extends(ScreenSpaceCanvas2D, _super);
  1094. /**
  1095. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  1096. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  1097. * All caching strategies will be available.
  1098. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  1099. * @param scene the Scene that owns the Canvas
  1100. * @param settings a combination of settings, possible ones are
  1101. * - children: an array of direct children primitives
  1102. * - id: a text identifier, for information purpose only
  1103. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  1104. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  1105. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  1106. * - width: the width of the Canvas. you can alternatively use the size setting.
  1107. * - height: the height of the Canvas. you can alternatively use the size setting.
  1108. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  1109. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  1110. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  1111. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  1112. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  1113. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1114. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  1115. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  1116. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  1117. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1118. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1119. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1120. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  1121. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  1122. */
  1123. function ScreenSpaceCanvas2D(scene, settings) {
  1124. BABYLON.Prim2DBase._isCanvasInit = true;
  1125. _super.call(this, scene, settings);
  1126. }
  1127. ScreenSpaceCanvas2D = __decorate([
  1128. BABYLON.className("ScreenSpaceCanvas2D")
  1129. ], ScreenSpaceCanvas2D);
  1130. return ScreenSpaceCanvas2D;
  1131. })(Canvas2D);
  1132. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  1133. })(BABYLON || (BABYLON = {}));