Scene.hx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. package h2d;
  2. import hxd.Math;
  3. /**
  4. Viewport alignment when scaling mode supports it. See `ScaleMode`.
  5. **/
  6. enum ScaleModeAlign {
  7. /** Anchor Scene viewport horizontally to the left side of the window. When passed to `verticalAlign` it will be treated as Center. **/
  8. Left;
  9. /** Anchor Scene viewport horizontally to the right side of the window. When passed to `verticalAlign` it will be treated as Center. **/
  10. Right;
  11. /** Anchor to the center of the window. **/
  12. Center;
  13. /** Anchor Scene viewport vertically to the top of the window. When passed to `horizontalAlign` it will be treated as Center. **/
  14. Top;
  15. /** Anchor Scene viewport vertically to the bottom of the window. When passed to `horizontalAlign` it will be treated as Center. **/
  16. Bottom;
  17. }
  18. /**
  19. Scaling mode of the 2D Scene.
  20. Set via `Scene.scaleMode`.
  21. See ScaleMode2D sample for usage showcase.
  22. **/
  23. enum ScaleMode {
  24. /**
  25. Matches scene size to window size. `width` and `height` of Scene will match window size. Default scaling mode.
  26. **/
  27. Resize;
  28. /**
  29. Sets constant Scene size and stretches it to cover entire window. This behavior is same as old `setFixedSize` method.
  30. @param width The width of the internal Scene viewport.
  31. @param height The height of the internal Scene viewport.
  32. **/
  33. Stretch(width : Int, height : Int);
  34. /**
  35. Sets constant Scene size and upscales it with preserving the aspect-ratio to fit the window.
  36. With `800x600` window, `LetterBox(320, 260)` will result in center-aligned Scene of size `320x260` upscaled to fit into the window.
  37. With same window but setting of `LetterBox(320, 260, true, Left, Top)` would result in the same Scene internal size,
  38. upscaled to `640x480` resolution and anchored to the top-left corner of the window.
  39. Note that while it's called LetterBox, there is no viewport rendering clipping apart from the out-of-bounds culling in `RenderContext.drawTile` / `Object.emitTile`.
  40. @param width The width of the internal Scene viewport.
  41. @param height The height of the internal Scene viewport.
  42. @param integerScale When enabled, upscaling is performed only with integer increments (1x, 2x, 3x, etc) and can be used to achieve pixel-perfect scaling.
  43. While enabled, the Scene won't be downscaled when internal viewport is larger than the window size and will remain at 1x zoom. Default: `false`.
  44. @param horizontalAlign The horizontal viewport anchoring rule. Accepted values are `Left`, `Center` and `Right`. Default: `Center`.
  45. @param verticalAlign The vertical viewport anchoring rule. Accepted values are `Top`, `Center` and `Bottom`. Default: `Center`.
  46. **/
  47. LetterBox(width : Int, height : Int, ?integerScale : Bool, ?horizontalAlign : ScaleModeAlign, ?verticalAlign : ScaleModeAlign);
  48. /**
  49. Sets constant Scene size, scale and alignment. Does not perform any adaptation to the window size apart from alignment.
  50. With `800x600` window, `Fixed(200, 150, 2, Left, Center)` will result in the Scene size of `200x150`, and visually upscaled to `400x300`, and aligned to a middle-left of the window.
  51. @param width The width of the internal Scene viewport.
  52. @param height The height of the internal Scene viewport.
  53. @param zoom The scaling multiplier of internal viewport when rendering onto the screen.
  54. @param horizontalAlign The horizontal viewport anchoring rule. Accepted values are `Left`, `Center` and `Right`. Default: `Center`.
  55. @param verticalAlign The vertical viewport anchoring rule. Accepted values are `Top`, `Center` and `Bottom`. Default: `Center`.
  56. **/
  57. Fixed(width : Int, height: Int, zoom : Float, ?horizontalAlign : ScaleModeAlign, ?verticalAlign : ScaleModeAlign);
  58. /**
  59. Upscales/downscales the Scene internal viewport according to `level` and matches Scene size to `ceil(window size / level)`.
  60. With `800x600` window, `Zoom(2)` will result in the `400x300` Scene size upscaled to fill the entire window.
  61. **/
  62. Zoom(level : Float);
  63. /**
  64. Ensures that the Scene size will be of the minimum specified size.
  65. Automatically calculates zoom level based on provided size according to `min(window width / min width, window height / min height)`, then applies same scaling as `Zoom(level)`.
  66. The behavior is similar to `LetterBox`, however instead of constant internal viewport size, Scene size will change to cover the entire window.
  67. `minWidth` or `minHeight` can be set to `0` in order to force scaling adjustment account only for either horizontal of vertical window size.
  68. If both are `0`, results are undefined.
  69. With `800x600` window, `AutoZoom(320, 260, false)` will result in the Scene size of `347x260`. `AutoZoom(320, 260, true)` will result in the size of `400x300`.
  70. @param minWidth The minimum width of the internal Scene viewport.
  71. @param minHeight The minimum height of the internal Scene viewport.
  72. @param integerScale When enabled, upscaling is performed only with integer increments (1x, 2x, 3x, etc) and can be used to achieve pixel-perfect scaling.
  73. While enabled, the Scene won't be downscaled when internal viewport is larger than the window size and will remain at 1x zoom. Default: `false`.
  74. **/
  75. AutoZoom(minWidth : Int, minHeight : Int, ?integerScaling : Bool);
  76. }
  77. /**
  78. The root class for a 2D scene. All root objects are added to it before being drawn on screen.
  79. **/
  80. class Scene extends Layers implements h3d.IDrawable implements hxd.SceneEvents.InteractiveScene {
  81. /**
  82. The current width (in pixels) of the scene. Can change if the screen gets resized or `scaleMode` changes.
  83. **/
  84. public var width(default,null) : Int;
  85. /**
  86. The current height (in pixels) of the scene. Can change if the screen gets resized or `scaleMode` changes.
  87. **/
  88. public var height(default, null) : Int;
  89. /**
  90. Viewport horizontal scale transform value. Converts from scene space to screen space of [0, 2] range.
  91. **/
  92. var viewportA(default, null) : Float;
  93. /**
  94. Viewport vertical scale transform value. Converts from scene space to screen space of [0, 2] range.
  95. **/
  96. var viewportD(default, null) : Float;
  97. /**
  98. Horizontal viewport offset relative to top-left corner of the window. Can change if the screen gets resized or `scaleMode` changes.
  99. Offset is in screen-space coordinates: [-1, 1] where 0 is center of the window.
  100. **/
  101. var viewportX(default, null) : Float;
  102. /**
  103. Vertical viewport offset relative to top-left corner of the window. Can change if the screen gets resized or `scaleMode` changes.
  104. Offset is in screen-space coordinates: [-1, 1] where 0 is center of the window.
  105. **/
  106. var viewportY(default, null) : Float;
  107. /**
  108. Horizontal viewport offset relative to top-left corner of the window in pixels.
  109. Assigned if the screen gets resized or `scaleMode` changes.
  110. **/
  111. var offsetX(default, null) : Float;
  112. /**
  113. Vertical viewport offset relative to top-left corner of the window in pixels.
  114. Assigned if the screen gets resized or `scaleMode` changes.
  115. **/
  116. var offsetY(default, null) : Float;
  117. /**
  118. Horizontal scale of a scene when rendering to the screen.
  119. Can change if the screen gets resized or `scaleMode` changes.
  120. **/
  121. public var viewportScaleX(default, null) : Float;
  122. /**
  123. Vertical scale of a scene when rendering to the screen.
  124. Can change if the screen gets resized or `scaleMode` changes.
  125. **/
  126. public var viewportScaleY(default, null) : Float;
  127. /**
  128. The current mouse X coordinates (in pixels) relative to the current `Scene.interactiveCamera`.
  129. **/
  130. public var mouseX(get, null) : Float;
  131. /**
  132. The current mouse Y coordinates (in pixels) relative to the current `Scene.interactiveCamera`.
  133. **/
  134. public var mouseY(get, null) : Float;
  135. /**
  136. The zoom factor of the scene, allows to set a fixed x2, x4 etc. zoom for pixel art
  137. When setting a zoom > 0, the scene resize will be automatically managed.
  138. **/
  139. @:deprecated("zoom is deprecated, use scaleMode = Zoom(v) instead")
  140. @:dox(hide)
  141. public var zoom(get, set) : Int;
  142. /**
  143. Scene scaling mode.
  144. Important thing to keep in mind - Scene does not clip rendering to it's scaled size and
  145. graphics can render outside of it. However `RenderContext.drawTile` (and consecutively `Object.emitTile`) does check for those bounds and
  146. will clip out tiles that are outside of the scene bounds.
  147. **/
  148. public var scaleMode(default, set) : ScaleMode = Resize;
  149. /**
  150. List of all cameras attached to the Scene. Should contain at least one camera to render (created by default).
  151. Override `h2d.Camera.layerVisible` method to filter out specific layers from camera rendering.
  152. To add or remove cameras use `Scene.addCamera` and `Scene.removeCamera` methods.
  153. **/
  154. public var cameras(get, never) : haxe.ds.ReadOnlyArray<Camera>;
  155. var _cameras : Array<Camera>;
  156. /**
  157. Alias to the first camera in the camera list: `cameras[0]`
  158. **/
  159. public var camera(get, never) : Camera;
  160. /**
  161. Camera instance that handles the scene events.
  162. Due to Heaps structure, only one Camera can work with the Interactives.
  163. Contrary to rendering, event handling does not check if layer is visible for the camera or not.
  164. Should never be null. When set, if Camera does not belong to the Scene, it will be added with `Scene.addCamera`.
  165. Would cause an exception when trying to remove current interactive camera from the list.
  166. **/
  167. public var interactiveCamera(default, set) : Camera;
  168. /**
  169. Controls the default value for `h2d.Drawable.smooth`. Default: `false`
  170. **/
  171. public var defaultSmooth(get, set) : Bool;
  172. /**
  173. The current Scene renderer. Can be customized.
  174. **/
  175. public var renderer(get, set) : RenderContext;
  176. var interactive : Array<Interactive>;
  177. var eventListeners : Array< hxd.Event -> Void >;
  178. var ctx : RenderContext;
  179. var window : hxd.Window;
  180. @:allow(h2d.Interactive)
  181. var events : hxd.SceneEvents;
  182. var shapePoint : h2d.col.Point;
  183. /**
  184. Create a new 2D scene. A default 2D scene is already available in `hxd.App.s2d`.
  185. **/
  186. public function new() {
  187. super(null);
  188. var e = h3d.Engine.getCurrent();
  189. ctx = new RenderContext(this);
  190. _cameras = [];
  191. new Camera(this);
  192. interactiveCamera = camera;
  193. width = e.width;
  194. height = e.height;
  195. viewportA = 2 / e.width;
  196. viewportD = 2 / e.height;
  197. viewportX = -1;
  198. viewportY = -1;
  199. viewportScaleX = 1;
  200. viewportScaleY = 1;
  201. offsetX = 0;
  202. offsetY = 0;
  203. interactive = new Array();
  204. eventListeners = new Array();
  205. shapePoint = new h2d.col.Point();
  206. window = hxd.Window.getInstance();
  207. posChanged = true;
  208. }
  209. inline function get_defaultSmooth() return ctx.defaultSmooth;
  210. inline function set_defaultSmooth(v) return ctx.defaultSmooth = v;
  211. @:dox(hide) @:noCompletion
  212. public function setEvents(events : hxd.SceneEvents) {
  213. this.events = events;
  214. }
  215. function get_zoom() : Int {
  216. return switch ( scaleMode ) {
  217. case Zoom(level): Std.int(level);
  218. default: 0;
  219. }
  220. }
  221. function set_zoom(v:Int) {
  222. scaleMode = Zoom(v);
  223. return v;
  224. }
  225. function set_scaleMode( v : ScaleMode ) {
  226. scaleMode = v;
  227. checkResize();
  228. return v;
  229. }
  230. function get_renderer() return ctx;
  231. function set_renderer(v) { ctx = v; return v; }
  232. inline function get_camera() return _cameras[0];
  233. inline function get_cameras() return _cameras;
  234. function set_interactiveCamera( cam : Camera ) {
  235. if ( cam == null ) throw "Interactive cammera cannot be null!";
  236. if ( cam.scene != this ) this.addCamera(cam);
  237. return interactiveCamera = cam;
  238. }
  239. /**
  240. Adds a Camera to the Scene camera list with optional index at which it is added.
  241. @param cam The Camera instance to add.
  242. @param pos Optional index at which the camera will be inserted.
  243. **/
  244. public function addCamera( cam : Camera, ?pos : Int ) {
  245. if ( cam.scene != null )
  246. cam.scene.removeCamera(cam);
  247. cam.scene = this;
  248. cam.posChanged = true;
  249. if ( pos != null ) _cameras.insert(pos, cam);
  250. else _cameras.push(cam);
  251. }
  252. /**
  253. Removes the Camera from the Scene camera list.
  254. Attempting to remove current `Scene.interactiveCamera` would cause an exception.
  255. **/
  256. public function removeCamera( cam : Camera ) {
  257. if ( cam == interactiveCamera ) throw "Current interactive Camera cannot be removed from camera list!";
  258. cam.scene = null;
  259. _cameras.remove(cam);
  260. }
  261. /**
  262. Set the fixed size for the scene, will prevent automatic scene resizing when screen size changes.
  263. **/
  264. @:deprecated("setFixedSize is deprecated, use scaleMode = Stretch(w, h) instead")
  265. @:dox(hide) @:noCompletion
  266. public function setFixedSize( w : Int, h : Int ) {
  267. scaleMode = Stretch(w, h);
  268. }
  269. /**
  270. Recalculates the scene viewport parameters based on `scaleMode`.
  271. **/
  272. @:dox(hide) @:noCompletion
  273. public function checkResize() {
  274. var engine = h3d.Engine.getCurrent();
  275. if (engine == null) return;
  276. inline function setSceneSize( w : Int, h : Int ) {
  277. if ( w != this.width || h != this.height ) {
  278. width = w;
  279. height = h;
  280. posChanged = true;
  281. }
  282. }
  283. inline function setViewportScale( sx : Float, sy : Float ) {
  284. viewportScaleX = sx;
  285. viewportScaleY = sy;
  286. }
  287. inline function calcViewport( horizontal : ScaleModeAlign, vertical : ScaleModeAlign, zoom : Float ) {
  288. viewportA = (zoom * 2) / engine.width;
  289. viewportD = (zoom * 2) / engine.height;
  290. setViewportScale(zoom, zoom);
  291. if ( horizontal == null ) horizontal = Center;
  292. switch ( horizontal ) {
  293. case Left:
  294. viewportX = -1;
  295. offsetX = 0;
  296. case Right:
  297. viewportX = 1 - (width * viewportA);
  298. offsetX = engine.width - width * zoom;
  299. default:
  300. // Simple `width * viewportA - 0.5` causes gaps between tiles
  301. viewportX = Math.floor((engine.width - width * zoom) / (zoom * 2)) * viewportA - 1.;
  302. offsetX = Math.floor((engine.width - width * zoom) / 2);
  303. }
  304. if ( vertical == null ) vertical = Center;
  305. switch ( vertical ) {
  306. case Top:
  307. viewportY = -1;
  308. offsetY = 0;
  309. case Bottom:
  310. viewportY = 1 - (height * viewportD);
  311. offsetY = engine.height - height * zoom;
  312. default:
  313. viewportY = Math.floor((engine.height - height * zoom) / (zoom * 2)) * viewportD - 1.;
  314. offsetY = Math.floor((engine.height - height * zoom) / 2);
  315. }
  316. }
  317. inline function zeroViewport() {
  318. viewportA = 2 / width;
  319. viewportD = 2 / height;
  320. viewportX = -1;
  321. viewportY = -1;
  322. }
  323. switch ( scaleMode ) {
  324. case Resize:
  325. setSceneSize(engine.width, engine.height);
  326. setViewportScale(1, 1);
  327. zeroViewport();
  328. case Stretch(_width, _height):
  329. setSceneSize(_width, _height);
  330. setViewportScale(engine.width / _width, engine.height / _height);
  331. zeroViewport();
  332. case LetterBox(_width, _height, integerScale, horizontalAlign, verticalAlign):
  333. setSceneSize(_width, _height);
  334. var zoom = Math.min(engine.width / _width, engine.height / _height);
  335. if ( integerScale ) {
  336. zoom = Std.int(zoom);
  337. if (zoom == 0) zoom = 1;
  338. }
  339. calcViewport(horizontalAlign, verticalAlign, zoom);
  340. case Fixed(_width, _height, zoom, horizontalAlign, verticalAlign):
  341. setSceneSize(_width, _height);
  342. calcViewport(horizontalAlign, verticalAlign, zoom);
  343. case Zoom(level):
  344. setSceneSize(Math.ceil(engine.width / level), Math.ceil(engine.height / level));
  345. setViewportScale(level, level);
  346. zeroViewport();
  347. case AutoZoom(minWidth, minHeight, integerScaling):
  348. var zoom = Math.min(engine.width / minWidth, engine.height / minHeight);
  349. if ( integerScaling ) {
  350. zoom = Std.int(zoom);
  351. if ( zoom == 0 ) zoom = 1;
  352. }
  353. setSceneSize(Math.ceil(engine.width / zoom), Math.ceil(engine.height / zoom));
  354. setViewportScale(zoom, zoom);
  355. zeroViewport();
  356. }
  357. }
  358. inline function screenXToViewport(mx:Float) {
  359. return @:privateAccess interactiveCamera.screenXToCamera(window.mouseX, window.mouseY);
  360. }
  361. inline function screenYToViewport(my:Float) {
  362. return @:privateAccess interactiveCamera.screenYToCamera(window.mouseX, window.mouseY);
  363. }
  364. function get_mouseX() {
  365. syncPos();
  366. var dx = screenXToViewport(window.mouseX) - absX;
  367. if( matC == 0 ) return dx / matA;
  368. var dy = screenYToViewport(window.mouseY) - absY;
  369. return (dx * matD - dy * matC) / (matA * matD - matB * matC);
  370. }
  371. function get_mouseY() {
  372. syncPos();
  373. var dy = screenYToViewport(window.mouseY) - absY;
  374. if( matB == 0 ) return dy / matD;
  375. var dx = screenXToViewport(window.mouseX) - absX;
  376. return (dy * matA - dx * matB) / (matA * matD - matB * matC);
  377. }
  378. @:dox(hide) @:noCompletion
  379. public function dispatchListeners( event : hxd.Event ) {
  380. screenToViewport(event);
  381. for( l in eventListeners ) {
  382. l(event);
  383. if( !event.propagate ) break;
  384. }
  385. }
  386. @:dox(hide) @:noCompletion
  387. public function isInteractiveVisible( i : hxd.SceneEvents.Interactive ) : Bool {
  388. var s : Object = cast i;
  389. while( s != this ) {
  390. if( s == null || !s.visible ) return false;
  391. s = s.parent;
  392. }
  393. return true;
  394. }
  395. /**
  396. Returns the topmost visible Interactive at the specified coordinates.
  397. **/
  398. public function getInteractive( x : Float, y : Float ) : Interactive {
  399. var pt = shapePoint;
  400. for( i in interactive ) {
  401. if( i.posChanged ) i.syncPos();
  402. var dx = x - i.absX;
  403. var dy = y - i.absY;
  404. var rx = (dx * i.matD - dy * i.matC) * i.invDet;
  405. var ry = (dy * i.matA - dx * i.matB) * i.invDet;
  406. if (i.shape != null) {
  407. pt.set(rx + i.shapeX, ry + i.shapeY);
  408. if ( !i.shape.contains(pt) ) continue;
  409. } else {
  410. if( ry < 0 || rx < 0 || rx >= i.width || ry >= i.height )
  411. continue;
  412. }
  413. // check visibility
  414. var visible = true;
  415. var p : Object = i;
  416. while( p != null ) {
  417. if( !p.visible ) {
  418. visible = false;
  419. break;
  420. }
  421. p = p.parent;
  422. }
  423. if( !visible ) continue;
  424. return i;
  425. }
  426. return null;
  427. }
  428. function screenToViewport( e : hxd.Event ) {
  429. interactiveCamera.eventToCamera(e);
  430. }
  431. @:dox(hide) @:noCompletion
  432. public function dispatchEvent( event : hxd.Event, to : hxd.SceneEvents.Interactive ) {
  433. var i : Interactive = cast to;
  434. screenToViewport(event);
  435. var dx = event.relX - i.absX;
  436. var dy = event.relY - i.absY;
  437. var rx = (dx * i.matD - dy * i.matC) * i.invDet;
  438. var ry = (dy * i.matA - dx * i.matB) * i.invDet;
  439. event.relX = rx;
  440. event.relY = ry;
  441. i.handleEvent(event);
  442. }
  443. @:dox(hide) @:noCompletion
  444. public function handleEvent( event : hxd.Event, last : hxd.SceneEvents.Interactive ) : hxd.SceneEvents.Interactive {
  445. screenToViewport(event);
  446. var ex = event.relX;
  447. var ey = event.relY;
  448. var index = last == null ? 0 : interactive.indexOf(cast last) + 1;
  449. var pt = shapePoint;
  450. for( idx in index...interactive.length ) {
  451. var i = interactive[idx];
  452. if( i == null ) break;
  453. if( i.invDet == 0 ) {
  454. // some interactives might have not been yet updated
  455. // make sure they won't match the collider
  456. continue;
  457. }
  458. var dx = ex - i.absX;
  459. var dy = ey - i.absY;
  460. var rx = (dx * i.matD - dy * i.matC) * i.invDet;
  461. var ry = (dy * i.matA - dx * i.matB) * i.invDet;
  462. if ( i.shape != null ) {
  463. // Check collision for Shape Interactive.
  464. pt.set(rx + i.shapeX,ry + i.shapeY);
  465. if ( !i.shape.contains(pt) ) continue;
  466. } else {
  467. // Check AABB for width/height Interactive.
  468. if( ry < 0 || rx < 0 || rx >= i.width || ry >= i.height )
  469. continue;
  470. }
  471. // check visibility
  472. var visible = true;
  473. var p : Object = i;
  474. while( p != null ) {
  475. if( !p.visible ) {
  476. visible = false;
  477. break;
  478. }
  479. p = p.parent;
  480. }
  481. if( !visible ) continue;
  482. event.relX = rx;
  483. event.relY = ry;
  484. i.handleEvent(event);
  485. if( event.cancel ) {
  486. event.cancel = false;
  487. event.propagate = false;
  488. continue;
  489. }
  490. return i;
  491. }
  492. return null;
  493. }
  494. /**
  495. Add an event listener that will capture all events that were not caught by an `h2d.Interactive`
  496. **/
  497. public function addEventListener( f : hxd.Event -> Void ) {
  498. eventListeners.push(f);
  499. }
  500. /**
  501. Remove a previously added event listener, returns false it was not part of the event listeners.
  502. **/
  503. public function removeEventListener( f : hxd.Event -> Void ) {
  504. for( e in eventListeners )
  505. if( Reflect.compareMethods(e, f) ) {
  506. eventListeners.remove(e);
  507. return true;
  508. }
  509. return false;
  510. }
  511. /**
  512. Starts input events capture and redirects them to `onEvent` method until `Scene.stopDrag` is called.
  513. While the method name may imply that only mouse events would be captured: This is not the case,
  514. as it will also capture all other input events, including keyboard events.
  515. @param onEvent A callback method that receives `hxd.Event` when input event happens.
  516. Unless `onEvent` sets `Event.propagate` to `true`, event won't be sent to other Interactives.
  517. @param onCancel An optional callback that is invoked when `Scene.stopDrag` is called.
  518. @param refEvent For touch events, when defined, only capture events that match the reference `Event.touchId`.
  519. **/
  520. public function startCapture( onEvent : hxd.Event -> Void, ?onCancel : Void -> Void, ?touchId : Int ) {
  521. events.startCapture(function(e) {
  522. screenToViewport(e);
  523. onEvent(e);
  524. },onCancel, touchId);
  525. }
  526. /**
  527. Stops current input event capture.
  528. **/
  529. public function stopCapture() {
  530. events.stopCapture();
  531. }
  532. @:deprecated("Renamed to startCapture") @:dox(hide)
  533. public inline function startDrag( onEvent : hxd.Event -> Void, ?onCancel : Void -> Void, ?refEvent : hxd.Event ) {
  534. startCapture(onEvent, onCancel, refEvent != null ? refEvent.touchId : null);
  535. }
  536. @:deprecated("Renamed to stopCapture") @:dox(hide)
  537. public inline function stopDrag() {
  538. stopCapture();
  539. }
  540. /**
  541. Get the currently focused Interactive.
  542. **/
  543. public function getFocus() : Interactive {
  544. if( events == null )
  545. return null;
  546. var f = events.getFocus();
  547. if( f == null )
  548. return null;
  549. var i = hxd.impl.Api.downcast(f, h2d.Interactive);
  550. if( i == null )
  551. return null;
  552. return interactive[interactive.indexOf(i)];
  553. }
  554. @:allow(h2d)
  555. function addEventTarget(i:Interactive) {
  556. // sort by which is over the other in the scene hierarchy
  557. inline function getLevel(i:Object) {
  558. var lv = 0;
  559. while( i != null ) {
  560. i = i.parent;
  561. lv++;
  562. }
  563. return lv;
  564. }
  565. inline function indexOf(p:Object, i:Object) {
  566. var id = -1;
  567. for( k in 0...p.children.length )
  568. if( p.children[k] == i ) {
  569. id = k;
  570. break;
  571. }
  572. return id;
  573. }
  574. var level = getLevel(i);
  575. for( index in 0...interactive.length ) {
  576. var i1 : Object = i;
  577. var i2 : Object = interactive[index];
  578. var lv1 = level;
  579. var lv2 = getLevel(i2);
  580. var p1 : Object = i1;
  581. var p2 : Object = i2;
  582. while( lv1 > lv2 ) {
  583. i1 = p1;
  584. p1 = p1.parent;
  585. lv1--;
  586. }
  587. while( lv2 > lv1 ) {
  588. i2 = p2;
  589. p2 = p2.parent;
  590. lv2--;
  591. }
  592. while( p1 != p2 ) {
  593. i1 = p1;
  594. p1 = p1.parent;
  595. i2 = p2;
  596. p2 = p2.parent;
  597. }
  598. if( indexOf(p1,i1) > indexOf(p2,i2) ) {
  599. interactive.insert(index, i);
  600. return;
  601. }
  602. }
  603. interactive.push(i);
  604. }
  605. @:allow(h2d)
  606. function removeEventTarget(i,notify=false) {
  607. interactive.remove(i);
  608. if( notify && events != null )
  609. @:privateAccess events.onRemove(i);
  610. }
  611. /**
  612. Dispose the scene and all its children, freeing used GPU memory.
  613. If Scene was allocated, causes `Object.onRemove` on all Scene objects.
  614. **/
  615. public function dispose() {
  616. if( allocated )
  617. onRemove();
  618. ctx.dispose();
  619. }
  620. /**
  621. <span class="label">Internal usage</span>
  622. Before `Scene.render` or `Scene.sync` are called, allows to set how much time has elapsed (in seconds) since the last frame in order to update scene animations.
  623. This is managed automatically by hxd.App.
  624. **/
  625. public function setElapsedTime( v : Float ) {
  626. ctx.elapsedTime = v;
  627. }
  628. function drawImplTo( s : Object, texs : Array<h3d.mat.Texture>, ?outputs : Array<hxsl.Output> ) {
  629. for( t in texs )
  630. if( !t.flags.has(Target) )
  631. throw "Can only draw to texture created with Target flag";
  632. ctx.engine = h3d.Engine.getCurrent();
  633. var oldBG = ctx.engine.backgroundColor;
  634. var inRender = @:privateAccess ctx.engine.inRender;
  635. ctx.engine.backgroundColor = null; // prevent clear bg
  636. ctx.globalAlpha = alpha;
  637. if( !inRender ) { // don't reset current tex stack
  638. ctx.engine.begin();
  639. ctx.begin();
  640. } else if( @:privateAccess ctx.targetFlipY == 0 )
  641. ctx.begin(); // ctx was never init, most likely a new scene
  642. ctx.pushTargets(texs);
  643. if( outputs != null ) @:privateAccess ctx.manager.setOutput(outputs);
  644. s.drawRec(ctx);
  645. if( outputs != null ) @:privateAccess ctx.manager.setOutput();
  646. ctx.popTarget();
  647. ctx.engine.backgroundColor = oldBG;
  648. if( !inRender ) {
  649. ctx.end();
  650. ctx.engine.end();
  651. }
  652. }
  653. /**
  654. Synchronize the scene without rendering, updating all objects and animations by the given amount of time, in seconds.
  655. **/
  656. public function syncOnly( et : Float ) {
  657. var engine = h3d.Engine.getCurrent();
  658. setElapsedTime(et);
  659. ctx.engine = engine;
  660. ctx.frame++;
  661. ctx.time += ctx.elapsedTime;
  662. ctx.globalAlpha = alpha;
  663. sync(ctx);
  664. }
  665. /**
  666. <span class="label">Internal usage</span>
  667. Render the scene on the screen.
  668. **/
  669. public function render( engine : h3d.Engine ) {
  670. ctx.engine = engine;
  671. ctx.frame++;
  672. ctx.time += ctx.elapsedTime;
  673. ctx.globalAlpha = alpha;
  674. sync(ctx);
  675. if( children.length == 0 ) return;
  676. ctx.begin();
  677. #if sceneprof h3d.impl.SceneProf.begin("2d", ctx.frame); #end
  678. ctx.drawScene();
  679. #if sceneprof h3d.impl.SceneProf.end(); #end
  680. ctx.end();
  681. }
  682. override function sync( ctx : RenderContext ) {
  683. var forceCamSync = posChanged;
  684. if( !allocated )
  685. onAdd();
  686. super.sync(ctx);
  687. for ( cam in cameras ) cam.sync(ctx, forceCamSync);
  688. }
  689. override function clipBounds(ctx:RenderContext, bounds:h2d.col.Bounds, scaleX = 1., scaleY = 1.)
  690. {
  691. // See Object.clipBounds for special notes on why Scene clipper always outputs entire viewport.
  692. // In short: Cameras.
  693. var matA, matB, matC, matD, absX, absY;
  694. @:privateAccess if( ctx.inFilter != null ) {
  695. var f1 = ctx.baseShader.filterMatrixA;
  696. var f2 = ctx.baseShader.filterMatrixB;
  697. var tmpA = this.matA * f1.x + this.matB * f1.y;
  698. var tmpB = this.matA * f2.x + this.matB * f2.y;
  699. var tmpC = this.matC * f1.x + this.matD * f1.y;
  700. var tmpD = this.matC * f2.x + this.matD * f2.y;
  701. var tmpX = this.absX * f1.x + this.absY * f1.y + f1.z;
  702. var tmpY = this.absX * f2.x + this.absY * f2.y + f2.z;
  703. matA = (tmpA * ctx.viewA + tmpB * ctx.viewC) / scaleX;
  704. matB = (tmpA * ctx.viewB + tmpB * ctx.viewD) / scaleY;
  705. matC = (tmpC * ctx.viewA + tmpD * ctx.viewC) / scaleX;
  706. matD = (tmpC * ctx.viewB + tmpD * ctx.viewD) / scaleY;
  707. absX = (tmpX * ctx.viewA + tmpY * ctx.viewC + ctx.viewX);
  708. absY = (tmpX * ctx.viewB + tmpY * ctx.viewD + ctx.viewY);
  709. } else {
  710. matA = (this.matA * ctx.viewA + this.matB * ctx.viewC) / scaleX;
  711. matB = (this.matA * ctx.viewB + this.matB * ctx.viewD) / scaleY;
  712. matC = (this.matC * ctx.viewA + this.matD * ctx.viewC) / scaleX;
  713. matD = (this.matC * ctx.viewB + this.matD * ctx.viewD) / scaleY;
  714. absX = (this.absX * ctx.viewA + this.absY * ctx.viewC + ctx.viewX);
  715. absY = (this.absX * ctx.viewB + this.absY * ctx.viewD + ctx.viewY);
  716. }
  717. var invDet = 1 / (matA * matD - matB * matC);
  718. bounds.xMin = ( (-1 - absX) * matD + (absY + 1 ) * matC ) * invDet;
  719. bounds.yMin = ( (absX + 1 ) * matB + (-1 - absY) * matA ) * invDet;
  720. bounds.xMax = ( (1 - absX ) * matD + (absY - 1 ) * matC ) * invDet;
  721. bounds.yMax = ( (absX - 1 ) * matB + (1 - absY ) * matA ) * invDet;
  722. }
  723. override function drawContent(ctx:RenderContext)
  724. {
  725. if( ctx.front2back ) {
  726. for ( cam in cameras ) {
  727. if ( !cam.visible ) continue;
  728. var i = children.length;
  729. var l = layerCount;
  730. cam.enter(ctx);
  731. while ( l-- > 0 ) {
  732. var top = l == 0 ? 0 : layersIndexes[l - 1];
  733. if ( cam.layerVisible(l) ) {
  734. while ( i >= top ) {
  735. children[i--].drawRec(ctx);
  736. }
  737. } else {
  738. i = top - 1;
  739. }
  740. }
  741. cam.exit(ctx);
  742. }
  743. draw(ctx);
  744. } else {
  745. draw(ctx);
  746. for ( cam in cameras ) {
  747. if ( !cam.visible ) continue;
  748. var i = 0;
  749. var l = 0;
  750. cam.enter(ctx);
  751. while ( l < layerCount ) {
  752. var top = layersIndexes[l++];
  753. if ( cam.layerVisible(l - 1) ) {
  754. while ( i < top ) {
  755. children[i++].drawRec(ctx);
  756. }
  757. } else {
  758. i = top;
  759. }
  760. }
  761. cam.exit(ctx);
  762. }
  763. }
  764. }
  765. override function onAdd() {
  766. checkResize();
  767. super.onAdd();
  768. window.addResizeEvent(checkResize);
  769. }
  770. override function onRemove() {
  771. super.onRemove();
  772. window.removeResizeEvent(checkResize);
  773. }
  774. /**
  775. Capture the scene into a texture and returns the resulting `h2d.Bitmap`.
  776. @param target Optional Tile to render onto. If not set, new Texture with interval Scene viewport dimensions is allocated,
  777. otherwise Tile boundaries and Texture are used.
  778. **/
  779. public function captureBitmap( ?target : Tile ) {
  780. var engine = h3d.Engine.getCurrent();
  781. if( target == null ) {
  782. var tex = new h3d.mat.Texture(width, height, [Target]);
  783. target = new Tile(tex,0, 0, width, height);
  784. }
  785. engine.begin();
  786. engine.setRenderZone(Std.int(target.x), Std.int(target.y), hxd.Math.ceil(target.width), hxd.Math.ceil(target.height));
  787. var tex = target.getTexture();
  788. engine.pushTarget(tex);
  789. var ow = width, oh = height, ova = viewportA, ovd = viewportD, ovx = viewportX, ovy = viewportY;
  790. width = tex.width;
  791. height = tex.height;
  792. viewportA = 2 / width;
  793. viewportD = 2 / height;
  794. viewportX = -1;
  795. viewportY = -1;
  796. posChanged = true;
  797. render(engine);
  798. engine.popTarget();
  799. width = ow;
  800. height = oh;
  801. viewportA = ova;
  802. viewportD = ovd;
  803. viewportX = ovx;
  804. viewportY = ovy;
  805. posChanged = true;
  806. engine.setRenderZone();
  807. engine.end();
  808. return new Bitmap(target);
  809. }
  810. }