CCClippingNode.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /****************************************************************************
  2. Copyright (c) 2010-2013 cocos2d-x.org
  3. Copyright (c) 2008-2010 Ricardo Quesada
  4. Copyright (c) 2011 Zynga Inc.
  5. Copyright (c) 2012 Pierre-David Bélanger
  6. http://www.cocos2d-x.org
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. ****************************************************************************/
  23. cc.stencilBits = -1;
  24. cc.setProgram = function (node, program) {
  25. node.setShaderProgram(program);
  26. var children = node.getChildren();
  27. if (!children)
  28. return;
  29. for (var i = 0; i < children.length; i++)
  30. cc.setProgram(children[i], program);
  31. };
  32. /**
  33. * <p>
  34. * cc.ClippingNode is a subclass of cc.Node. <br/>
  35. * It draws its content (childs) clipped using a stencil. <br/>
  36. * The stencil is an other cc.Node that will not be drawn. <br/>
  37. * The clipping is done using the alpha part of the stencil (adjusted with an alphaThreshold).
  38. * </p>
  39. * @class
  40. * @extends cc.Node
  41. */
  42. cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{
  43. _stencil: null,
  44. _alphaThreshold: 0,
  45. _inverted: false,
  46. _godhelpme: false,
  47. ctor: function () {
  48. cc.Node.prototype.ctor.call(this);
  49. this._stencil = null;
  50. this._alphaThreshold = 0;
  51. this._inverted = false;
  52. },
  53. /**
  54. * Initializes a clipping node with an other node as its stencil. <br/>
  55. * The stencil node will be retained, and its parent will be set to this clipping node.
  56. * @param {cc.Node} [stencil=null]
  57. */
  58. init: null,
  59. _initForWebGL: function (stencil) {
  60. this._stencil = stencil;
  61. this._alphaThreshold = 1;
  62. this._inverted = false;
  63. // get (only once) the number of bits of the stencil buffer
  64. cc.ClippingNode._init_once = true;
  65. if (cc.ClippingNode._init_once) {
  66. cc.stencilBits = cc.renderContext.getParameter(cc.renderContext.STENCIL_BITS);
  67. if (cc.stencilBits <= 0)
  68. cc.log("Stencil buffer is not enabled.");
  69. cc.ClippingNode._init_once = false;
  70. }
  71. return true;
  72. },
  73. _initForCanvas: function (stencil) {
  74. this._stencil = stencil;
  75. this._alphaThreshold = 1;
  76. this._inverted = false;
  77. },
  78. onEnter: function () {
  79. cc.Node.prototype.onEnter.call(this);
  80. this._stencil.onEnter();
  81. },
  82. onEnterTransitionDidFinish: function () {
  83. cc.Node.prototype.onEnterTransitionDidFinish.call(this);
  84. this._stencil.onEnterTransitionDidFinish();
  85. },
  86. onExitTransitionDidStart: function () {
  87. this._stencil.onExitTransitionDidStart();
  88. cc.Node.prototype.onExitTransitionDidStart.call(this);
  89. },
  90. onExit: function () {
  91. this._stencil.onExit();
  92. cc.Node.prototype.onExit.call(this);
  93. },
  94. visit: null,
  95. _visitForWebGL: function (ctx) {
  96. var gl = ctx || cc.renderContext;
  97. // if stencil buffer disabled
  98. if (cc.stencilBits < 1) {
  99. // draw everything, as if there where no stencil
  100. cc.Node.prototype.visit.call(this, ctx);
  101. return;
  102. }
  103. // return fast (draw nothing, or draw everything if in inverted mode) if:
  104. // - nil stencil node
  105. // - or stencil node invisible:
  106. if (!this._stencil || !this._stencil.isVisible()) {
  107. if (this._inverted)
  108. cc.Node.prototype.visit.call(this, ctx); // draw everything
  109. return;
  110. }
  111. // store the current stencil layer (position in the stencil buffer),
  112. // this will allow nesting up to n CCClippingNode,
  113. // where n is the number of bits of the stencil buffer.
  114. cc.ClippingNode._layer = -1;
  115. // all the _stencilBits are in use?
  116. if (cc.ClippingNode._layer + 1 == cc.stencilBits) {
  117. // warn once
  118. cc.ClippingNode._visit_once = true;
  119. if (cc.ClippingNode._visit_once) {
  120. cc.log("Nesting more than " + cc.stencilBits + "stencils is not supported. Everything will be drawn without stencil for this node and its childs.");
  121. cc.ClippingNode._visit_once = false;
  122. }
  123. // draw everything, as if there where no stencil
  124. cc.Node.prototype.visit.call(this, ctx);
  125. return;
  126. }
  127. ///////////////////////////////////
  128. // INIT
  129. // increment the current layer
  130. cc.ClippingNode._layer++;
  131. // mask of the current layer (ie: for layer 3: 00000100)
  132. var mask_layer = 0x1 << cc.ClippingNode._layer;
  133. // mask of all layers less than the current (ie: for layer 3: 00000011)
  134. var mask_layer_l = mask_layer - 1;
  135. // mask of all layers less than or equal to the current (ie: for layer 3: 00000111)
  136. var mask_layer_le = mask_layer | mask_layer_l;
  137. // manually save the stencil state
  138. var currentStencilEnabled = gl.isEnabled(gl.STENCIL_TEST);
  139. var currentStencilWriteMask = gl.getParameter(gl.STENCIL_WRITEMASK);
  140. var currentStencilFunc = gl.getParameter(gl.STENCIL_FUNC);
  141. var currentStencilRef = gl.getParameter(gl.STENCIL_REF);
  142. var currentStencilValueMask = gl.getParameter(gl.STENCIL_VALUE_MASK);
  143. var currentStencilFail = gl.getParameter(gl.STENCIL_FAIL);
  144. var currentStencilPassDepthFail = gl.getParameter(gl.STENCIL_PASS_DEPTH_FAIL);
  145. var currentStencilPassDepthPass = gl.getParameter(gl.STENCIL_PASS_DEPTH_PASS);
  146. // enable stencil use
  147. gl.enable(gl.STENCIL_TEST);
  148. // check for OpenGL error while enabling stencil test
  149. //cc.CHECK_GL_ERROR_DEBUG();
  150. // all bits on the stencil buffer are readonly, except the current layer bit,
  151. // this means that operation like glClear or glStencilOp will be masked with this value
  152. gl.stencilMask(mask_layer);
  153. // manually save the depth test state
  154. //GLboolean currentDepthTestEnabled = GL_TRUE;
  155. //currentDepthTestEnabled = glIsEnabled(GL_DEPTH_TEST);
  156. var currentDepthWriteMask = gl.getParameter(gl.DEPTH_WRITEMASK);
  157. // disable depth test while drawing the stencil
  158. //glDisable(GL_DEPTH_TEST);
  159. // disable update to the depth buffer while drawing the stencil,
  160. // as the stencil is not meant to be rendered in the real scene,
  161. // it should never prevent something else to be drawn,
  162. // only disabling depth buffer update should do
  163. gl.depthMask(false);
  164. ///////////////////////////////////
  165. // CLEAR STENCIL BUFFER
  166. // manually clear the stencil buffer by drawing a fullscreen rectangle on it
  167. // setup the stencil test func like this:
  168. // for each pixel in the fullscreen rectangle
  169. // never draw it into the frame buffer
  170. // if not in inverted mode: set the current layer value to 0 in the stencil buffer
  171. // if in inverted mode: set the current layer value to 1 in the stencil buffer
  172. gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
  173. gl.stencilOp(!this._inverted ? gl.ZERO : gl.REPLACE, gl.KEEP, gl.KEEP);
  174. // draw a fullscreen solid rectangle to clear the stencil buffer
  175. //ccDrawSolidRect(CCPointZero, ccpFromSize([[CCDirector sharedDirector] winSize]), ccc4f(1, 1, 1, 1));
  176. cc.drawingUtil.drawSolidRect(cc.PointZero(), cc.pFromSize(cc.Director.getInstance().getWinSize()), cc.c4f(1, 1, 1, 1));
  177. ///////////////////////////////////
  178. // DRAW CLIPPING STENCIL
  179. // setup the stencil test func like this:
  180. // for each pixel in the stencil node
  181. // never draw it into the frame buffer
  182. // if not in inverted mode: set the current layer value to 1 in the stencil buffer
  183. // if in inverted mode: set the current layer value to 0 in the stencil buffer
  184. gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
  185. gl.stencilOp(!this._inverted ? gl.REPLACE : gl.ZERO, gl.KEEP, gl.KEEP);
  186. if (this._alphaThreshold < 1) {
  187. // since glAlphaTest do not exists in OES, use a shader that writes
  188. // pixel only if greater than an alpha threshold
  189. var program = cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST);
  190. var alphaValueLocation = gl.getUniformLocation(program.getProgram(), cc.UNIFORM_ALPHA_TEST_VALUE_S);
  191. // set our alphaThreshold
  192. cc.glUseProgram(program.getProgram());
  193. program.setUniformLocationWith1f(alphaValueLocation, this._alphaThreshold);
  194. // we need to recursively apply this shader to all the nodes in the stencil node
  195. // XXX: we should have a way to apply shader to all nodes without having to do this
  196. cc.setProgram(this._stencil, program);
  197. }
  198. // draw the stencil node as if it was one of our child
  199. // (according to the stencil test func/op and alpha (or alpha shader) test)
  200. cc.kmGLPushMatrix();
  201. this.transform();
  202. this._stencil.visit();
  203. cc.kmGLPopMatrix();
  204. // restore alpha test state
  205. //if (this._alphaThreshold < 1) {
  206. // XXX: we need to find a way to restore the shaders of the stencil node and its childs
  207. //}
  208. // restore the depth test state
  209. gl.depthMask(currentDepthWriteMask);
  210. //if (currentDepthTestEnabled) {
  211. // glEnable(GL_DEPTH_TEST);
  212. //}
  213. ///////////////////////////////////
  214. // DRAW CONTENT
  215. // setup the stencil test func like this:
  216. // for each pixel of this node and its childs
  217. // if all layers less than or equals to the current are set to 1 in the stencil buffer
  218. // draw the pixel and keep the current layer in the stencil buffer
  219. // else
  220. // do not draw the pixel but keep the current layer in the stencil buffer
  221. gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le);
  222. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  223. // draw (according to the stencil test func) this node and its childs
  224. cc.Node.prototype.visit.call(this, ctx);
  225. ///////////////////////////////////
  226. // CLEANUP
  227. // manually restore the stencil state
  228. gl.stencilFunc(currentStencilFunc, currentStencilRef, currentStencilValueMask);
  229. gl.stencilOp(currentStencilFail, currentStencilPassDepthFail, currentStencilPassDepthPass);
  230. gl.stencilMask(currentStencilWriteMask);
  231. if (!currentStencilEnabled)
  232. gl.disable(gl.STENCIL_TEST);
  233. // we are done using this layer, decrement
  234. cc.ClippingNode._layer--;
  235. },
  236. _visitForCanvas: function (ctx) {
  237. // return fast (draw nothing, or draw everything if in inverted mode) if:
  238. // - nil stencil node
  239. // - or stencil node invisible:
  240. if (!this._stencil || !this._stencil.isVisible()) {
  241. if (this._inverted)
  242. cc.Node.prototype.visit.call(this, ctx); // draw everything
  243. return;
  244. }
  245. // Composition mode, costy but support texture stencil
  246. if (this._cangodhelpme() || this._stencil instanceof cc.Sprite) {
  247. var context = ctx || cc.renderContext;
  248. // Cache the current canvas, for later use (This is a little bit heavy, replace this solution with other walkthrough)
  249. var canvas = context.canvas;
  250. var locCache = cc.ClippingNode._getSharedCache();
  251. locCache.width = canvas.width;
  252. locCache.height = canvas.height;
  253. var locCacheCtx = locCache.getContext("2d");
  254. locCacheCtx.drawImage(canvas, 0, 0);
  255. context.save();
  256. // Draw everything first using node visit function
  257. this._super(context);
  258. context.globalCompositeOperation = this._inverted ? "destination-out" : "destination-in";
  259. this.transform(context);
  260. this._stencil.visit();
  261. context.restore();
  262. // Redraw the cached canvas, so that the cliped area shows the background etc.
  263. context.save();
  264. context.setTransform(1, 0, 0, 1, 0, 0);
  265. context.globalCompositeOperation = "destination-over";
  266. context.drawImage(locCache, 0, 0);
  267. context.restore();
  268. }
  269. // Clip mode, fast, but only support cc.DrawNode
  270. else {
  271. var context = ctx || cc.renderContext, i, children = this._children, locChild;
  272. context.save();
  273. this.transform(context);
  274. this._stencil.visit(context);
  275. context.clip();
  276. // Clip mode doesn't support recusive stencil, so once we used a clip stencil,
  277. // so if it has ClippingNode as a child, the child must uses composition stencil.
  278. this._cangodhelpme(true);
  279. var len = children.length;
  280. if (len > 0) {
  281. this.sortAllChildren();
  282. // draw children zOrder < 0
  283. for (i = 0; i < len; i++) {
  284. locChild = children[i];
  285. if (locChild._zOrder < 0)
  286. locChild.visit(context);
  287. else
  288. break;
  289. }
  290. this.draw(context);
  291. for (; i < len; i++) {
  292. children[i].visit(context);
  293. }
  294. } else
  295. this.draw(context);
  296. this._cangodhelpme(false);
  297. context.restore();
  298. }
  299. },
  300. /**
  301. * The cc.Node to use as a stencil to do the clipping. <br/>
  302. * The stencil node will be retained. This default to nil.
  303. * @return {cc.Node}
  304. */
  305. getStencil: function () {
  306. return this._stencil;
  307. },
  308. /**
  309. * @param {cc.Node} stencil
  310. */
  311. setStencil: null,
  312. _setStencilForWebGL: function (stencil) {
  313. this._stencil = stencil;
  314. },
  315. _setStencilForCanvas: function (stencil) {
  316. this._stencil = stencil;
  317. var locEGL_ScaleX = cc.EGLView.getInstance().getScaleX(), locEGL_ScaleY = cc.EGLView.getInstance().getScaleY();
  318. var locContext = cc.renderContext;
  319. // For texture stencil, use the sprite itself
  320. if (stencil instanceof cc.Sprite) {
  321. return;
  322. }
  323. // For shape stencil, rewrite the draw of stencil ,only init the clip path and draw nothing.
  324. else if (stencil instanceof cc.DrawNode) {
  325. stencil.draw = function () {
  326. for (var i = 0; i < stencil._buffer.length; i++) {
  327. var element = stencil._buffer[i];
  328. var vertices = element.verts;
  329. var firstPoint = vertices[0];
  330. locContext.beginPath();
  331. locContext.moveTo(firstPoint.x * locEGL_ScaleX, -firstPoint.y * locEGL_ScaleY);
  332. for (var j = 1, len = vertices.length; j < len; j++)
  333. locContext.lineTo(vertices[j].x * locEGL_ScaleX, -vertices[j].y * locEGL_ScaleY);
  334. }
  335. }
  336. }
  337. },
  338. /**
  339. * <p>
  340. * The alpha threshold. <br/>
  341. * The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. <br/>
  342. * Should be a float between 0 and 1. <br/>
  343. * This default to 1 (so alpha test is disabled).
  344. * </P>
  345. * @return {Number}
  346. */
  347. getAlphaThreshold: function () {
  348. return this._alphaThreshold;
  349. },
  350. /**
  351. * set alpha threshold.
  352. * @param {Number} alphaThreshold
  353. */
  354. setAlphaThreshold: function (alphaThreshold) {
  355. this._alphaThreshold = alphaThreshold;
  356. },
  357. /**
  358. * <p>
  359. * Inverted. If this is set to YES, <br/>
  360. * the stencil is inverted, so the content is drawn where the stencil is NOT drawn. <br/>
  361. * This default to NO.
  362. * </p>
  363. * @return {Boolean}
  364. */
  365. isInverted: function () {
  366. return this._inverted;
  367. },
  368. /**
  369. * set whether or not invert of stencil
  370. * @param {Boolean} inverted
  371. */
  372. setInverted: function (inverted) {
  373. this._inverted = inverted;
  374. },
  375. _cangodhelpme: function (godhelpme) {
  376. if (godhelpme === true || godhelpme === false)
  377. cc.ClippingNode.prototype._godhelpme = godhelpme;
  378. return cc.ClippingNode.prototype._godhelpme;
  379. }
  380. });
  381. if (cc.Browser.supportWebGL) {
  382. //WebGL
  383. cc.ClippingNode.prototype.init = cc.ClippingNode.prototype._initForWebGL;
  384. cc.ClippingNode.prototype.visit = cc.ClippingNode.prototype._visitForWebGL;
  385. cc.ClippingNode.prototype.setStencil = cc.ClippingNode.prototype._setStencilForWebGL;
  386. } else {
  387. cc.ClippingNode.prototype.init = cc.ClippingNode.prototype._initForCanvas;
  388. cc.ClippingNode.prototype.visit = cc.ClippingNode.prototype._visitForCanvas;
  389. cc.ClippingNode.prototype.setStencil = cc.ClippingNode.prototype._setStencilForCanvas;
  390. }
  391. cc.ClippingNode._init_once = null;
  392. cc.ClippingNode._visit_once = null;
  393. cc.ClippingNode._layer = null;
  394. cc.ClippingNode._sharedCache = null;
  395. cc.ClippingNode._getSharedCache = function () {
  396. return (cc.ClippingNode._sharedCache) || (cc.ClippingNode._sharedCache = document.createElement("canvas"));
  397. }
  398. /**
  399. * Creates and initializes a clipping node with an other node as its stencil. <br/>
  400. * The stencil node will be retained.
  401. * @param {cc.Node} [stencil=null]
  402. * @return {cc.ClippingNode}
  403. */
  404. cc.ClippingNode.create = function (stencil) {
  405. var node = new cc.ClippingNode();
  406. node.init(stencil);
  407. return node;
  408. };