babylon.group2d.ts 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. module BABYLON {
  2. @className("Group2D")
  3. /**
  4. * A non renderable primitive that defines a logical group.
  5. * Can also serve the purpose of caching its content into a bitmap to reduce rendering overhead
  6. */
  7. export class Group2D extends Prim2DBase {
  8. static GROUP2D_PROPCOUNT: number = Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  9. public static sizeProperty: Prim2DPropInfo;
  10. public static actualSizeProperty: Prim2DPropInfo;
  11. /**
  12. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  13. */
  14. public static GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  15. /**
  16. * When used, this group's content won't be cached, no matter which strategy used.
  17. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  18. */
  19. public static GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  20. /**
  21. * When used, the group's content will be cached in the nearest cached parent group/canvas
  22. */
  23. public static GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  24. /**
  25. * Create an Logical or Renderable Group.
  26. * @param settings a combination of settings, possible ones are
  27. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  28. * - children: an array of direct children
  29. * - id a text identifier, for information purpose
  30. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  31. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  32. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  33. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  34. * - zOrder: override the zOrder with the specified value
  35. * - origin: define the normalized origin point location, default [0.5;0.5]
  36. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  37. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  38. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  39. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  40. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  41. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  42. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  47. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  48. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  49. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  50. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  51. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  52. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  53. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  54. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  55. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  56. */
  57. constructor(settings?: {
  58. parent ?: Prim2DBase,
  59. children ?: Array<Prim2DBase>,
  60. id ?: string,
  61. position ?: Vector2,
  62. x ?: number,
  63. y ?: number,
  64. scale ?: number,
  65. scaleX ?: number,
  66. scaleY ?: number,
  67. trackNode ?: Node,
  68. opacity ?: number,
  69. zOrder ?: number,
  70. origin ?: Vector2,
  71. size ?: Size,
  72. width ?: number,
  73. height ?: number,
  74. cacheBehavior ?: number,
  75. layoutEngine ?: LayoutEngineBase | string,
  76. isVisible ?: boolean,
  77. isPickable ?: boolean,
  78. isContainer ?: boolean,
  79. childrenFlatZOrder?: boolean,
  80. marginTop ?: number | string,
  81. marginLeft ?: number | string,
  82. marginRight ?: number | string,
  83. marginBottom ?: number | string,
  84. margin ?: number | string,
  85. marginHAlignment ?: number,
  86. marginVAlignment ?: number,
  87. marginAlignment ?: string,
  88. paddingTop ?: number | string,
  89. paddingLeft ?: number | string,
  90. paddingRight ?: number | string,
  91. paddingBottom ?: number | string,
  92. padding ?: string,
  93. }) {
  94. if (settings == null) {
  95. settings = {};
  96. }
  97. if (settings.origin == null) {
  98. settings.origin = new Vector2(0, 0);
  99. }
  100. super(settings);
  101. let size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new Size(settings.width || 0, settings.height || 0)));
  102. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  103. if (this._trackedNode && this.owner) {
  104. this.owner._registerTrackedNode(this);
  105. }
  106. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  107. this.size = size;
  108. this._viewportPosition = Vector2.Zero();
  109. }
  110. static _createCachedCanvasGroup(owner: Canvas2D): Group2D {
  111. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: Vector2.Zero(), origin: Vector2.Zero(), size: null, isVisible: true, isPickable: false });
  112. return g;
  113. }
  114. protected applyCachedTexture(vertexData: VertexData, material: StandardMaterial) {
  115. this._bindCacheTarget();
  116. if (vertexData) {
  117. var uv = vertexData.uvs;
  118. let nodeuv = this._renderableData._cacheNodeUVs;
  119. for (let i = 0; i < 4; i++) {
  120. uv[i * 2 + 0] = nodeuv[i].x;
  121. uv[i * 2 + 1] = nodeuv[i].y;
  122. }
  123. }
  124. if (material) {
  125. material.diffuseTexture = this._renderableData._cacheTexture;
  126. material.emissiveColor = new Color3(1, 1, 1);
  127. }
  128. this._renderableData._cacheTexture.hasAlpha = true;
  129. this._unbindCacheTarget();
  130. }
  131. /**
  132. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  133. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  134. */
  135. public get cachedRect(): PackedRect {
  136. if (!this._renderableData) {
  137. return null;
  138. }
  139. return this._renderableData._cacheNode;
  140. }
  141. /**
  142. * The UVs into the MapTexture that map the cached group
  143. */
  144. public get cachedUVs(): Vector2[] {
  145. if (!this._renderableData) {
  146. return null;
  147. }
  148. return this._renderableData._cacheNodeUVs;
  149. }
  150. public get cachedUVsChanged(): Observable<Vector2[]> {
  151. if (!this._renderableData) {
  152. return null;
  153. }
  154. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  155. this._renderableData._cacheNodeUVsChangedObservable = new Observable<Vector2[]>();
  156. }
  157. return this._renderableData._cacheNodeUVsChangedObservable;
  158. }
  159. /**
  160. * Access the texture that maintains a cached version of the Group2D.
  161. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  162. */
  163. public get cacheTexture(): MapTexture {
  164. if (!this._renderableData) {
  165. return null;
  166. }
  167. return this._renderableData._cacheTexture;
  168. }
  169. /**
  170. * Call this method to remove this Group and its children from the Canvas
  171. */
  172. public dispose(): boolean {
  173. if (!super.dispose()) {
  174. return false;
  175. }
  176. if (this._trackedNode != null) {
  177. this.owner._unregisterTrackedNode(this);
  178. this._trackedNode = null;
  179. }
  180. if (this._renderableData) {
  181. this._renderableData.dispose(this.owner.engine);
  182. this._renderableData = null;
  183. }
  184. return true;
  185. }
  186. /**
  187. * @returns Returns true if the Group render content, false if it's a logical group only
  188. */
  189. public get isRenderableGroup(): boolean {
  190. return this._isRenderableGroup;
  191. }
  192. /**
  193. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  194. */
  195. public get isCachedGroup(): boolean {
  196. return this._isCachedGroup;
  197. }
  198. @instanceLevelProperty(Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, pi => Group2D.sizeProperty = pi, false, true)
  199. public get size(): Size {
  200. return this._size;
  201. }
  202. /**
  203. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  204. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  205. */
  206. public set size(val: Size) {
  207. this._size = val;
  208. }
  209. public get viewportSize(): ISize {
  210. return this._viewportSize;
  211. }
  212. @instanceLevelProperty(Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, pi => Group2D.actualSizeProperty = pi)
  213. /**
  214. * Get the actual size of the group, if the size property is not null, this value will be the same, but if size is null, actualSize will return the size computed from the group's bounding content.
  215. */
  216. public get actualSize(): Size {
  217. // The computed size will be floor on both width and height
  218. let actualSize: Size;
  219. // Return the size if set by the user
  220. if (this._size) {
  221. actualSize = new Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  222. }
  223. // Otherwise the size is computed based on the boundingInfo
  224. else {
  225. let m = this.boundingInfo.max();
  226. actualSize = new Size(Math.ceil(m.x), Math.ceil(m.y));
  227. }
  228. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  229. if (!actualSize.equals(this._actualSize)) {
  230. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  231. this._actualSize = actualSize;
  232. this.handleGroupChanged(Group2D.actualSizeProperty);
  233. }
  234. return actualSize;
  235. }
  236. /**
  237. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  238. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  239. */
  240. public get cacheBehavior(): number {
  241. return this._cacheBehavior;
  242. }
  243. public _addPrimToDirtyList(prim: Prim2DBase) {
  244. this._renderableData._primDirtyList.push(prim);
  245. }
  246. public _renderCachedCanvas() {
  247. this.owner._addGroupRenderCount(1);
  248. this.updateCachedStates(true);
  249. let context = new PrepareRender2DContext();
  250. this._prepareGroupRender(context);
  251. this._groupRender();
  252. }
  253. /**
  254. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  255. */
  256. public get trackedNode(): Node {
  257. return this._trackedNode;
  258. }
  259. public set trackedNode(val: Node) {
  260. if (val != null) {
  261. if (!this._isFlagSet(SmartPropertyPrim.flagTrackedGroup)) {
  262. this.owner._registerTrackedNode(this);
  263. }
  264. this._trackedNode = val;
  265. } else {
  266. if (this._isFlagSet(SmartPropertyPrim.flagTrackedGroup)) {
  267. this.owner._unregisterTrackedNode(this);
  268. }
  269. this._trackedNode = null;
  270. }
  271. }
  272. protected levelIntersect(intersectInfo: IntersectInfo2D): boolean {
  273. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  274. return true;
  275. }
  276. protected updateLevelBoundingInfo() {
  277. let size: Size;
  278. // If the size is set by the user, the boundingInfo is computed from this value
  279. if (this.size) {
  280. size = this.size;
  281. }
  282. // Otherwise the group's level bounding info is "collapsed"
  283. else {
  284. size = new Size(0, 0);
  285. }
  286. BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  287. }
  288. // Method called only on renderable groups to prepare the rendering
  289. protected _prepareGroupRender(context: PrepareRender2DContext) {
  290. let sortedDirtyList: Prim2DBase[] = null;
  291. // Update the Global Transformation and visibility status of the changed primitives
  292. let rd = this._renderableData;
  293. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  294. sortedDirtyList = rd._primDirtyList.sort((a, b) => a.hierarchyDepth - b.hierarchyDepth);
  295. this.updateCachedStatesOf(sortedDirtyList, true);
  296. }
  297. // Setup the size of the rendering viewport
  298. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  299. if (!this._isCachedGroup) {
  300. // Compute the WebGL viewport's location/size
  301. let t = this._globalTransform.getTranslation();
  302. let s = this.actualSize.clone();
  303. let rs = this.owner._renderingSize;
  304. s.height = Math.min(s.height, rs.height - t.y);
  305. s.width = Math.min(s.width, rs.width - t.x);
  306. let x = t.x;
  307. let y = t.y;
  308. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  309. this._viewportPosition.x = x;
  310. this._viewportPosition.y = y;
  311. let vw = s.width;
  312. let vh = s.height;
  313. if (!this._viewportSize) {
  314. this._viewportSize = new Size(vw, vh);
  315. } else {
  316. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  317. context.forceRefreshPrimitive = true;
  318. }
  319. this._viewportSize.width = vw;
  320. this._viewportSize.height = vh;
  321. }
  322. }
  323. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  324. else {
  325. let newSize = this.actualSize.clone();
  326. if (!newSize.equals(this._viewportSize)) {
  327. context.forceRefreshPrimitive = true;
  328. }
  329. this._viewportSize = newSize;
  330. }
  331. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  332. // If the group is cached, set the dirty flag to true because of the incoming changes
  333. this._cacheGroupDirty = this._isCachedGroup;
  334. rd._primNewDirtyList.splice(0);
  335. // If it's a force refresh, prepare all the children
  336. if (context.forceRefreshPrimitive) {
  337. for (let p of this._children) {
  338. p._prepareRender(context);
  339. }
  340. } else {
  341. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  342. // the hierarchyDepth in order to prepare primitives from top to bottom
  343. if (!sortedDirtyList) {
  344. sortedDirtyList = rd._primDirtyList.sort((a, b) => a.hierarchyDepth - b.hierarchyDepth);
  345. }
  346. sortedDirtyList.forEach(p => {
  347. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  348. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  349. if (!p.isDisposed && p._needPrepare()) {
  350. p._prepareRender(context);
  351. }
  352. });
  353. }
  354. // Everything is updated, clear the dirty list
  355. rd._primDirtyList.forEach(p => {
  356. if (rd._primNewDirtyList.indexOf(p) === -1) {
  357. p._resetPropertiesDirty();
  358. } else {
  359. p._setFlags(SmartPropertyPrim.flagNeedRefresh);
  360. }
  361. });
  362. rd._primDirtyList.splice(0);
  363. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  364. }
  365. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  366. rd._childrenRenderableGroups.forEach(g => {
  367. g._prepareGroupRender(context);
  368. });
  369. }
  370. protected _groupRender() {
  371. let engine = this.owner.engine;
  372. let failedCount = 0;
  373. // First recurse to children render group to render them (in their cache or on screen)
  374. for (let childGroup of this._renderableData._childrenRenderableGroups) {
  375. childGroup._groupRender();
  376. }
  377. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  378. if (!this.isCachedGroup || this._cacheGroupDirty) {
  379. this.owner._addGroupRenderCount(1);
  380. if (this.isCachedGroup) {
  381. this._bindCacheTarget();
  382. } else {
  383. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  384. }
  385. let curAlphaTest = engine.getAlphaTesting() === true;
  386. let curDepthWrite = engine.getDepthWrite() === true;
  387. // ===================================================================
  388. // First pass, update the InstancedArray and render Opaque primitives
  389. // Disable Alpha Testing, Enable Depth Write
  390. engine.setAlphaTesting(false);
  391. engine.setDepthWrite(true);
  392. // For each different model of primitive to render
  393. let context = new Render2DContext(Render2DContext.RenderModeOpaque);
  394. this._renderableData._renderGroupInstancesInfo.forEach((k, v) => {
  395. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  396. let renderCount = this._prepareContext(engine, context, v);
  397. // If null is returned, there's no opaque data to render
  398. if (renderCount === null) {
  399. return;
  400. }
  401. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  402. if (!this.owner.supportInstancedArray || renderCount > 0) {
  403. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  404. let renderFailed = !v.modelRenderCache.render(v, context);
  405. // Update dirty flag/related
  406. v.opaqueDirty = renderFailed;
  407. failedCount += renderFailed ? 1 : 0;
  408. }
  409. });
  410. // =======================================================================
  411. // Second pass, update the InstancedArray and render AlphaTest primitives
  412. // Enable Alpha Testing, Enable Depth Write
  413. engine.setAlphaTesting(true);
  414. engine.setDepthWrite(true);
  415. // For each different model of primitive to render
  416. context = new Render2DContext(Render2DContext.RenderModeAlphaTest);
  417. this._renderableData._renderGroupInstancesInfo.forEach((k, v) => {
  418. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  419. let renderCount = this._prepareContext(engine, context, v);
  420. // If null is returned, there's no opaque data to render
  421. if (renderCount === null) {
  422. return;
  423. }
  424. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  425. if (!this.owner.supportInstancedArray || renderCount > 0) {
  426. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  427. let renderFailed = !v.modelRenderCache.render(v, context);
  428. // Update dirty flag/related
  429. v.opaqueDirty = renderFailed;
  430. failedCount += renderFailed ? 1 : 0;
  431. }
  432. });
  433. // =======================================================================
  434. // Third pass, transparent primitive rendering
  435. // Enable Alpha Testing, Disable Depth Write
  436. engine.setAlphaTesting(true);
  437. engine.setDepthWrite(false);
  438. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  439. if (this._renderableData._transparentListChanged) {
  440. this._updateTransparentData();
  441. }
  442. // From this point on we have up to date data to render, so let's go
  443. failedCount += this._renderTransparentData();
  444. // =======================================================================
  445. // Unbind target/restore viewport setting, clear dirty flag, and quit
  446. // The group's content is no longer dirty
  447. this._cacheGroupDirty = failedCount !== 0;
  448. if (this.isCachedGroup) {
  449. this._unbindCacheTarget();
  450. } else {
  451. if (curVP) {
  452. engine.setViewport(curVP);
  453. }
  454. }
  455. // Restore saved states
  456. engine.setAlphaTesting(curAlphaTest);
  457. engine.setDepthWrite(curDepthWrite);
  458. }
  459. }
  460. public _setCacheGroupDirty() {
  461. this._cacheGroupDirty = true;
  462. }
  463. private _updateTransparentData() {
  464. this.owner._addUpdateTransparentDataCount(1);
  465. let rd = this._renderableData;
  466. // Sort all the primitive from their depth, max (bottom) to min (top)
  467. rd._transparentPrimitives.sort((a, b) => b._primitive.actualZOffset - a._primitive.actualZOffset);
  468. let checkAndAddPrimInSegment = (seg: TransparentSegment, tpiI: number): boolean => {
  469. let tpi = rd._transparentPrimitives[tpiI];
  470. // Fast rejection: if gii are different
  471. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  472. return false;
  473. }
  474. //let tpiZ = tpi._primitive.actualZOffset;
  475. // We've made it so far, the tpi can be part of the segment, add it
  476. tpi._transparentSegment = seg;
  477. tpi._primitive._updateTransparentSegmentIndices(seg);
  478. return true;
  479. }
  480. // Free the existing TransparentSegments
  481. for (let ts of rd._transparentSegments) {
  482. ts.dispose(this.owner.engine);
  483. }
  484. rd._transparentSegments.splice(0);
  485. let prevSeg = null;
  486. for (let tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  487. let tpi = rd._transparentPrimitives[tpiI];
  488. // Check if the Data in which the primitive is stored is not sorted properly
  489. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  490. tpi._groupInstanceInfo.sortTransparentData();
  491. }
  492. // Reset the segment, we have to create/rebuild it
  493. tpi._transparentSegment = null;
  494. // If there's a previous valid segment, check if this prim can be part of it
  495. if (prevSeg) {
  496. checkAndAddPrimInSegment(prevSeg, tpiI);
  497. }
  498. // If we couldn't insert in the adjacent segments, he have to create one
  499. if (!tpi._transparentSegment) {
  500. let ts = new TransparentSegment();
  501. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  502. let prim = tpi._primitive;
  503. ts.startZ = prim.actualZOffset;
  504. prim._updateTransparentSegmentIndices(ts);
  505. ts.endZ = ts.startZ;
  506. tpi._transparentSegment = ts;
  507. rd._transparentSegments.push(ts);
  508. }
  509. // Update prevSeg
  510. prevSeg = tpi._transparentSegment;
  511. }
  512. //rd._firstChangedPrim = null;
  513. rd._transparentListChanged = false;
  514. }
  515. private _renderTransparentData(): number {
  516. let failedCount = 0;
  517. let context = new Render2DContext(Render2DContext.RenderModeTransparent);
  518. let rd = this._renderableData;
  519. let useInstanced = this.owner.supportInstancedArray;
  520. let length = rd._transparentSegments.length;
  521. for (let i = 0; i < length; i++) {
  522. context.instancedBuffers = null;
  523. let ts = rd._transparentSegments[i];
  524. let gii = ts.groupInsanceInfo;
  525. let mrc = gii.modelRenderCache;
  526. let engine = this.owner.engine;
  527. let count = ts.endDataIndex - ts.startDataIndex;
  528. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  529. // We don't want to create an Instanced Buffer for less that 5 prims
  530. if (useInstanced && count >= 5) {
  531. if (!ts.partBuffers) {
  532. let buffers = new Array<WebGLBuffer>();
  533. for (let j = 0; j < gii.transparentData.length; j++) {
  534. let gitd = gii.transparentData[j];
  535. let dfa = gitd._partData;
  536. let data = dfa.pack();
  537. let stride = dfa.stride;
  538. let neededSize = count * stride * 4;
  539. let buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  540. let segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  541. engine.updateArrayBuffer(segData);
  542. buffers.push(buffer);
  543. }
  544. ts.partBuffers = buffers;
  545. } else if (gii.transparentDirty) {
  546. for (let j = 0; j < gii.transparentData.length; j++) {
  547. let gitd = gii.transparentData[j];
  548. let dfa = gitd._partData;
  549. let data = dfa.pack();
  550. let stride = dfa.stride;
  551. let buffer = ts.partBuffers[j];
  552. let segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  553. engine.bindArrayBuffer(buffer);
  554. engine.updateArrayBuffer(segData);
  555. }
  556. }
  557. context.useInstancing = true;
  558. context.instancesCount = count;
  559. context.instancedBuffers = ts.partBuffers;
  560. context.groupInfoPartData = gii.transparentData;
  561. let renderFailed = !mrc.render(gii, context);
  562. failedCount += renderFailed ? 1 : 0;
  563. } else {
  564. context.useInstancing = false;
  565. context.partDataStartIndex = ts.startDataIndex;
  566. context.partDataEndIndex = ts.endDataIndex;
  567. context.groupInfoPartData = gii.transparentData;
  568. let renderFailed = !mrc.render(gii, context);
  569. failedCount += renderFailed ? 1 : 0;
  570. }
  571. }
  572. return failedCount;
  573. }
  574. private _prepareContext(engine: Engine, context: Render2DContext, gii: GroupInstanceInfo): number {
  575. let gipd: GroupInfoPartData[] = null;
  576. let setDirty: (dirty: boolean) => void;
  577. let getDirty: () => boolean;
  578. // Render Mode specifics
  579. switch (context.renderMode) {
  580. case Render2DContext.RenderModeOpaque:
  581. {
  582. if (!gii.hasOpaqueData) {
  583. return null;
  584. }
  585. setDirty = (dirty: boolean) => { gii.opaqueDirty = dirty; };
  586. getDirty = () => gii.opaqueDirty;
  587. context.groupInfoPartData = gii.opaqueData;
  588. gipd = gii.opaqueData;
  589. break;
  590. }
  591. case Render2DContext.RenderModeAlphaTest:
  592. {
  593. if (!gii.hasAlphaTestData) {
  594. return null;
  595. }
  596. setDirty = (dirty: boolean) => { gii.alphaTestDirty = dirty; };
  597. getDirty = () => gii.alphaTestDirty;
  598. context.groupInfoPartData = gii.alphaTestData;
  599. gipd = gii.alphaTestData;
  600. break;
  601. }
  602. default:
  603. throw new Error("_prepareContext is only for opaque or alphaTest");
  604. }
  605. let renderCount = 0;
  606. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  607. // Skip it if instanced arrays are not supported
  608. if (this.owner.supportInstancedArray) {
  609. // Flag for instancing
  610. context.useInstancing = true;
  611. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  612. for (let i = 0; i < gipd.length; i++) {
  613. let pid = gipd[i];
  614. // If the instances of the model was changed, pack the data
  615. let array = pid._partData;
  616. let instanceData = array.pack();
  617. renderCount += array.usedElementCount;
  618. // Compute the size the instance buffer should have
  619. let neededSize = array.usedElementCount * array.stride * 4;
  620. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  621. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  622. if (pid._partBuffer) {
  623. engine.deleteInstancesBuffer(pid._partBuffer);
  624. }
  625. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  626. pid._partBufferSize = neededSize;
  627. setDirty(false);
  628. // Update the WebGL buffer to match the new content of the instances data
  629. engine.updateArrayBuffer(instanceData);
  630. } else if (getDirty()) {
  631. // Update the WebGL buffer to match the new content of the instances data
  632. engine.bindArrayBuffer(pid._partBuffer);
  633. engine.updateArrayBuffer(instanceData);
  634. }
  635. }
  636. setDirty(false);
  637. }
  638. // Can't rely on hardware instancing, use the DynamicFloatArray instance, render its whole content
  639. else {
  640. context.partDataStartIndex = 0;
  641. // Find the first valid object to get the count
  642. if (context.groupInfoPartData.length > 0) {
  643. let i = 0;
  644. while (!context.groupInfoPartData[i]) {
  645. i++;
  646. }
  647. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  648. }
  649. }
  650. return renderCount;
  651. }
  652. protected _setRenderingScale(scale: number) {
  653. if (this._renderableData._renderingScale === scale) {
  654. return;
  655. }
  656. this._renderableData._renderingScale = scale;
  657. }
  658. private static _s = Size.Zero();
  659. private _bindCacheTarget() {
  660. let curWidth: number;
  661. let curHeight: number;
  662. let rd = this._renderableData;
  663. let rs = rd._renderingScale;
  664. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  665. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  666. let sizeChanged = !Group2D._s.equals(rd._cacheSize);
  667. if (rd._cacheNode) {
  668. let size = rd._cacheNode.contentSize;
  669. // Check if we have to deallocate because the size is too small
  670. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  671. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  672. // For World space: no over-provisioning
  673. let overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  674. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  675. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  676. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  677. rd._cacheTexture.freeRect(rd._cacheNode);
  678. rd._cacheNode = null;
  679. }
  680. }
  681. if (!rd._cacheNode) {
  682. // Check if we have to allocate a rendering zone in the global cache texture
  683. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  684. rd._cacheNode = res.node;
  685. rd._cacheTexture = res.texture;
  686. rd._cacheRenderSprite = res.sprite;
  687. sizeChanged = true;
  688. }
  689. if (sizeChanged) {
  690. rd._cacheSize.copyFrom(Group2D._s);
  691. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  692. this.scale = this._renderableData._renderingScale;
  693. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  694. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  695. }
  696. this._setFlags(SmartPropertyPrim.flagWorldCacheChanged);
  697. }
  698. let n = rd._cacheNode;
  699. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  700. }
  701. private _unbindCacheTarget() {
  702. if (this._renderableData._cacheTexture) {
  703. this._renderableData._cacheTexture.unbindTexture();
  704. }
  705. }
  706. protected handleGroupChanged(prop: Prim2DPropInfo) {
  707. // This method is only for cachedGroup
  708. let rd = this._renderableData;
  709. if (!rd) {
  710. return;
  711. }
  712. let cachedSprite = rd._cacheRenderSprite;
  713. if (!this.isCachedGroup || !cachedSprite) {
  714. return;
  715. }
  716. // For now we only support these property changes
  717. // TODO: add more! :)
  718. if (prop.id === Prim2DBase.actualPositionProperty.id) {
  719. cachedSprite.actualPosition = this.actualPosition.clone();
  720. if (cachedSprite.position != null) {
  721. cachedSprite.position = cachedSprite.actualPosition.clone();
  722. }
  723. } else if (prop.id === Prim2DBase.rotationProperty.id) {
  724. cachedSprite.rotation = this.rotation;
  725. } else if (prop.id === Prim2DBase.scaleProperty.id) {
  726. cachedSprite.scale = this.scale;
  727. } else if (prop.id === Prim2DBase.originProperty.id) {
  728. cachedSprite.origin = this.origin.clone();
  729. } else if (prop.id === Group2D.actualSizeProperty.id) {
  730. cachedSprite.size = this.actualSize.clone();
  731. //console.log(`[${this._globalTransformProcessStep}] Sync Sprite ${this.id}, width: ${this.actualSize.width}, height: ${this.actualSize.height}`);
  732. }
  733. }
  734. private detectGroupStates() {
  735. var isCanvas = this instanceof Canvas2D;
  736. var canvasStrat = this.owner.cachingStrategy;
  737. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  738. if (canvasStrat === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  739. this._isRenderableGroup = isCanvas;
  740. this._isCachedGroup = false;
  741. }
  742. // In Canvas cached only mode, only the Canvas is cached and renderable, all other groups are logicals
  743. else if (canvasStrat === Canvas2D.CACHESTRATEGY_CANVAS) {
  744. if (isCanvas) {
  745. this._isRenderableGroup = true;
  746. this._isCachedGroup = true;
  747. } else {
  748. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  749. this._isCachedGroup = false;
  750. }
  751. }
  752. // Top Level Groups cached only mode, the canvas is a renderable/not cached, its direct Groups are cached/renderable, all other group are logicals
  753. else if (canvasStrat === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  754. if (isCanvas) {
  755. this._isRenderableGroup = true;
  756. this._isCachedGroup = false;
  757. } else {
  758. if (this.hierarchyDepth === 1) {
  759. this._isRenderableGroup = true;
  760. this._isCachedGroup = true;
  761. } else {
  762. this._isRenderableGroup = false;
  763. this._isCachedGroup = false;
  764. }
  765. }
  766. }
  767. // All Group cached mode, all groups are renderable/cached, including the Canvas, groups with the behavior DONTCACHE are renderable/not cached, groups with CACHEINPARENT are logical ones
  768. else if (canvasStrat === Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  769. var gcb = this.cacheBehavior;
  770. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  771. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  772. this._isCachedGroup = false;
  773. }
  774. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  775. this._isRenderableGroup = true;
  776. this._isCachedGroup = true;
  777. }
  778. }
  779. if (this._isRenderableGroup) {
  780. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  781. if (!this._renderableData) {
  782. this._renderableData = new RenderableGroupData();
  783. }
  784. }
  785. // If the group is tagged as renderable we add it to the renderable tree
  786. if (this._isCachedGroup) {
  787. let cur = this.parent;
  788. while (cur) {
  789. if (cur instanceof Group2D && cur._isRenderableGroup) {
  790. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  791. cur._renderableData._childrenRenderableGroups.push(this);
  792. }
  793. break;
  794. }
  795. cur = cur.parent;
  796. }
  797. }
  798. }
  799. private _trackedNode: Node;
  800. protected _isRenderableGroup: boolean;
  801. protected _isCachedGroup: boolean;
  802. private _cacheGroupDirty: boolean;
  803. private _cacheBehavior: number;
  804. private _viewportPosition: Vector2;
  805. private _viewportSize: Size;
  806. public _renderableData: RenderableGroupData;
  807. }
  808. export class RenderableGroupData {
  809. constructor() {
  810. this._primDirtyList = new Array<Prim2DBase>();
  811. this._primNewDirtyList = new Array<Prim2DBase>();
  812. this._childrenRenderableGroups = new Array<Group2D>();
  813. this._renderGroupInstancesInfo = new StringDictionary<GroupInstanceInfo>();
  814. this._transparentPrimitives = new Array<TransparentPrimitiveInfo>();
  815. this._transparentSegments = new Array<TransparentSegment>();
  816. this._transparentListChanged = false;
  817. this._cacheNode = null;
  818. this._cacheTexture = null;
  819. this._cacheRenderSprite = null;
  820. this._renderingScale = 1;
  821. this._cacheNodeUVs = null;
  822. this._cacheNodeUVsChangedObservable = null;
  823. this._cacheSize = Size.Zero();
  824. this._useMipMap = false;
  825. this._anisotropicLevel = 1;
  826. }
  827. dispose(engine: Engine) {
  828. if (this._cacheRenderSprite) {
  829. this._cacheRenderSprite.dispose();
  830. this._cacheRenderSprite = null;
  831. }
  832. if (this._cacheTexture && this._cacheNode) {
  833. this._cacheTexture.freeRect(this._cacheNode);
  834. this._cacheTexture = null;
  835. this._cacheNode = null;
  836. }
  837. if (this._primDirtyList) {
  838. this._primDirtyList.splice(0);
  839. this._primDirtyList = null;
  840. }
  841. if (this._renderGroupInstancesInfo) {
  842. this._renderGroupInstancesInfo.forEach((k, v) => {
  843. v.dispose();
  844. });
  845. this._renderGroupInstancesInfo = null;
  846. }
  847. if (this._cacheNodeUVsChangedObservable) {
  848. this._cacheNodeUVsChangedObservable.clear();
  849. this._cacheNodeUVsChangedObservable = null;
  850. }
  851. if (this._transparentSegments) {
  852. for (let ts of this._transparentSegments) {
  853. ts.dispose(engine);
  854. }
  855. this._transparentSegments.splice(0);
  856. this._transparentSegments = null;
  857. }
  858. }
  859. addNewTransparentPrimitiveInfo(prim: RenderablePrim2D, gii: GroupInstanceInfo): TransparentPrimitiveInfo {
  860. let tpi = new TransparentPrimitiveInfo();
  861. tpi._primitive = prim;
  862. tpi._groupInstanceInfo = gii;
  863. tpi._transparentSegment = null;
  864. this._transparentPrimitives.push(tpi);
  865. this._transparentListChanged = true;
  866. return tpi;
  867. }
  868. removeTransparentPrimitiveInfo(tpi: TransparentPrimitiveInfo) {
  869. let index = this._transparentPrimitives.indexOf(tpi);
  870. if (index !== -1) {
  871. this._transparentPrimitives.splice(index, 1);
  872. this._transparentListChanged = true;
  873. }
  874. }
  875. transparentPrimitiveZChanged(tpi: TransparentPrimitiveInfo) {
  876. this._transparentListChanged = true;
  877. //this.updateSmallestZChangedPrim(tpi);
  878. }
  879. _primDirtyList: Array<Prim2DBase>;
  880. _primNewDirtyList: Array<Prim2DBase>;
  881. _childrenRenderableGroups: Array<Group2D>;
  882. _renderGroupInstancesInfo: StringDictionary<GroupInstanceInfo>;
  883. _cacheNode: PackedRect;
  884. _cacheTexture: MapTexture;
  885. _cacheRenderSprite: Sprite2D;
  886. _cacheNodeUVs: Vector2[];
  887. _cacheNodeUVsChangedObservable: Observable<Vector2[]>;
  888. _cacheSize: Size;
  889. _useMipMap: boolean;
  890. _anisotropicLevel: number;
  891. _transparentListChanged: boolean;
  892. _transparentPrimitives: Array<TransparentPrimitiveInfo>;
  893. _transparentSegments: Array<TransparentSegment>;
  894. _renderingScale: number;
  895. }
  896. export class TransparentPrimitiveInfo {
  897. _primitive: RenderablePrim2D;
  898. _groupInstanceInfo: GroupInstanceInfo;
  899. _transparentSegment: TransparentSegment;
  900. }
  901. }