Form.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. #include "Base.h"
  2. #include "Form.h"
  3. #include "AbsoluteLayout.h"
  4. #include "FlowLayout.h"
  5. #include "VerticalLayout.h"
  6. #include "Game.h"
  7. #include "Theme.h"
  8. #include "Label.h"
  9. #include "Button.h"
  10. #include "CheckBox.h"
  11. #include "Scene.h"
  12. // Default form shaders
  13. #define FORM_VSH "res/shaders/form.vert"
  14. #define FORM_FSH "res/shaders/form.frag"
  15. namespace gameplay
  16. {
  17. static Effect* __formEffect = NULL;
  18. static std::vector<Form*> __forms;
  19. Form::Form() : _theme(NULL), _frameBuffer(NULL), _spriteBatch(NULL), _node(NULL),
  20. _nodeQuad(NULL), _nodeMaterial(NULL) , _u2(0), _v1(0), _isGamepad(false)
  21. {
  22. }
  23. Form::~Form()
  24. {
  25. SAFE_DELETE(_spriteBatch);
  26. SAFE_RELEASE(_frameBuffer);
  27. SAFE_RELEASE(_theme);
  28. if (__formEffect)
  29. {
  30. if (__formEffect->getRefCount() == 1)
  31. {
  32. __formEffect->release();
  33. __formEffect = NULL;
  34. }
  35. }
  36. // Remove this Form from the global list.
  37. std::vector<Form*>::iterator it = std::find(__forms.begin(), __forms.end(), this);
  38. if (it != __forms.end())
  39. {
  40. __forms.erase(it);
  41. }
  42. }
  43. Form* Form::create(const char* id, Theme::Style* style, Layout::Type layoutType)
  44. {
  45. GP_ASSERT(style);
  46. Layout* layout;
  47. switch (layoutType)
  48. {
  49. case Layout::LAYOUT_ABSOLUTE:
  50. layout = AbsoluteLayout::create();
  51. break;
  52. case Layout::LAYOUT_FLOW:
  53. layout = FlowLayout::create();
  54. break;
  55. case Layout::LAYOUT_VERTICAL:
  56. layout = VerticalLayout::create();
  57. break;
  58. default:
  59. GP_ERROR("Unsupported layout type '%d'.", layoutType);
  60. break;
  61. }
  62. Form* form = new Form();
  63. if (id)
  64. form->_id = id;
  65. form->_style = style;
  66. form->_layout = layout;
  67. form->_theme = style->getTheme();
  68. form->_theme->addRef();
  69. form->updateFrameBuffer();
  70. __forms.push_back(form);
  71. return form;
  72. }
  73. Form* Form::create(const char* url)
  74. {
  75. // Load Form from .form file.
  76. Properties* properties = Properties::create(url);
  77. if (properties == NULL)
  78. {
  79. GP_ASSERT(properties);
  80. return NULL;
  81. }
  82. // Check if the Properties is valid and has a valid namespace.
  83. Properties* formProperties = (strlen(properties->getNamespace()) > 0) ? properties : properties->getNextNamespace();
  84. assert(formProperties);
  85. if (!formProperties || !(strcmp(formProperties->getNamespace(), "form") == 0))
  86. {
  87. GP_ASSERT(formProperties);
  88. SAFE_DELETE(properties);
  89. return NULL;
  90. }
  91. // Create new form with given ID, theme and layout.
  92. std::string themeFile;
  93. formProperties->getPath("theme", &themeFile);
  94. const char* layoutString = formProperties->getString("layout");
  95. Layout* layout;
  96. switch (getLayoutType(layoutString))
  97. {
  98. case Layout::LAYOUT_ABSOLUTE:
  99. layout = AbsoluteLayout::create();
  100. break;
  101. case Layout::LAYOUT_FLOW:
  102. layout = FlowLayout::create();
  103. break;
  104. case Layout::LAYOUT_VERTICAL:
  105. layout = VerticalLayout::create();
  106. break;
  107. default:
  108. GP_ERROR("Unsupported layout type '%d'.", getLayoutType(layoutString));
  109. break;
  110. }
  111. Theme* theme = Theme::create(themeFile.c_str());
  112. GP_ASSERT(theme);
  113. Form* form = new Form();
  114. form->_layout = layout;
  115. form->_theme = theme;
  116. Theme::Style* style = NULL;
  117. const char* styleName = formProperties->getString("style");
  118. if (styleName)
  119. {
  120. style = theme->getStyle(styleName);
  121. }
  122. else
  123. {
  124. style = theme->getEmptyStyle();
  125. }
  126. form->initialize(style, formProperties);
  127. form->_consumeInputEvents = formProperties->getBool("consumeInputEvents", false);
  128. form->_scroll = getScroll(formProperties->getString("scroll"));
  129. form->_scrollBarsAutoHide = formProperties->getBool("scrollBarsAutoHide");
  130. if (form->_scrollBarsAutoHide)
  131. {
  132. form->_scrollBarOpacity = 0.0f;
  133. }
  134. // Add all the controls to the form.
  135. form->addControls(theme, formProperties);
  136. SAFE_DELETE(properties);
  137. form->updateFrameBuffer();
  138. __forms.push_back(form);
  139. return form;
  140. }
  141. Form* Form::getForm(const char* id)
  142. {
  143. std::vector<Form*>::const_iterator it;
  144. for (it = __forms.begin(); it < __forms.end(); ++it)
  145. {
  146. Form* f = *it;
  147. GP_ASSERT(f);
  148. if (strcmp(id, f->getId()) == 0)
  149. {
  150. return f;
  151. }
  152. }
  153. return NULL;
  154. }
  155. Theme* Form::getTheme() const
  156. {
  157. return _theme;
  158. }
  159. void Form::updateFrameBuffer()
  160. {
  161. float width = _absoluteClipBounds.width;
  162. float height = _absoluteClipBounds.height;
  163. SAFE_RELEASE(_frameBuffer);
  164. SAFE_DELETE(_spriteBatch);
  165. if (width != 0.0f && height != 0.0f)
  166. {
  167. // Width and height must be powers of two to create a texture.
  168. unsigned int w = nextPowerOfTwo(width);
  169. unsigned int h = nextPowerOfTwo(height);
  170. _u2 = width / (float)w;
  171. _v1 = height / (float)h;
  172. _frameBuffer = FrameBuffer::create(_id.c_str(), w, h);
  173. GP_ASSERT(_frameBuffer);
  174. // Re-create projection matrix for drawing onto framebuffer
  175. Matrix::createOrthographicOffCenter(0, width, height, 0, 0, 1, &_projectionMatrix);
  176. // Re-create sprite batch
  177. _spriteBatch = SpriteBatch::create(_frameBuffer->getRenderTarget()->getTexture());
  178. GP_ASSERT(_spriteBatch);
  179. // Compute full-viewport ortho matrix for drawing frame buffer onto screen
  180. Matrix viewportProjection;
  181. Matrix::createOrthographicOffCenter(0, Game::getInstance()->getViewport().width, Game::getInstance()->getViewport().height, 0, 0, 1, &viewportProjection);
  182. _spriteBatch->setProjectionMatrix(viewportProjection);
  183. // Clear the framebuffer black
  184. Game* game = Game::getInstance();
  185. FrameBuffer* previousFrameBuffer = _frameBuffer->bind();
  186. Rectangle previousViewport = game->getViewport();
  187. game->setViewport(Rectangle(0, 0, width, height));
  188. _theme->setProjectionMatrix(_projectionMatrix);
  189. game->clear(Game::CLEAR_COLOR, Vector4::zero(), 1.0, 0);
  190. previousFrameBuffer->bind();
  191. game->setViewport(previousViewport);
  192. // Force any attached node to be updated
  193. setNode(_node);
  194. }
  195. }
  196. static Effect* createEffect()
  197. {
  198. Effect* effect = NULL;
  199. if (__formEffect == NULL)
  200. {
  201. __formEffect = Effect::createFromFile(FORM_VSH, FORM_FSH);
  202. if (__formEffect == NULL)
  203. {
  204. GP_ERROR("Unable to load form effect.");
  205. return NULL;
  206. }
  207. effect = __formEffect;
  208. }
  209. else
  210. {
  211. effect = __formEffect;
  212. }
  213. return effect;
  214. }
  215. void Form::setNode(Node* node)
  216. {
  217. // If we were already attached to a node, remove ourself from it
  218. if (_node)
  219. {
  220. _node->setModel(NULL);
  221. _nodeQuad = NULL;
  222. _nodeMaterial = NULL;
  223. _node = NULL;
  224. }
  225. if (node)
  226. {
  227. // Set this Form up to be 3D by initializing a quad.
  228. float x2 = _absoluteBounds.width;
  229. float y2 = _absoluteBounds.height;
  230. float vertices[] =
  231. {
  232. 0, y2, 0, 0, _v1,
  233. 0, 0, 0, 0, 0,
  234. x2, y2, 0, _u2, _v1,
  235. x2, 0, 0, _u2, 0
  236. };
  237. VertexFormat::Element elements[] =
  238. {
  239. VertexFormat::Element(VertexFormat::POSITION, 3),
  240. VertexFormat::Element(VertexFormat::TEXCOORD0, 2)
  241. };
  242. Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 2), 4, false);
  243. GP_ASSERT(mesh);
  244. mesh->setPrimitiveType(Mesh::TRIANGLE_STRIP);
  245. mesh->setVertexData(vertices, 0, 4);
  246. _nodeQuad = Model::create(mesh);
  247. SAFE_RELEASE(mesh);
  248. GP_ASSERT(_nodeQuad);
  249. // Create the effect and material
  250. Effect* effect = createEffect();
  251. GP_ASSERT(effect);
  252. _nodeMaterial = Material::create(effect);
  253. GP_ASSERT(_nodeMaterial);
  254. _nodeQuad->setMaterial(_nodeMaterial);
  255. _nodeMaterial->release();
  256. node->setModel(_nodeQuad);
  257. _nodeQuad->release();
  258. // Bind the WorldViewProjection matrix.
  259. _nodeMaterial->setParameterAutoBinding("u_worldViewProjectionMatrix", RenderState::WORLD_VIEW_PROJECTION_MATRIX);
  260. // Bind the texture from the framebuffer and set the texture to clamp
  261. if (_frameBuffer)
  262. {
  263. Texture::Sampler* sampler = Texture::Sampler::create(_frameBuffer->getRenderTarget()->getTexture());
  264. GP_ASSERT(sampler);
  265. sampler->setWrapMode(Texture::CLAMP, Texture::CLAMP);
  266. _nodeMaterial->getParameter("u_texture")->setValue(sampler);
  267. sampler->release();
  268. }
  269. RenderState::StateBlock* rsBlock = _nodeMaterial->getStateBlock();
  270. rsBlock->setDepthWrite(true);
  271. rsBlock->setBlend(true);
  272. rsBlock->setBlendSrc(RenderState::BLEND_SRC_ALPHA);
  273. rsBlock->setBlendDst(RenderState::BLEND_ONE_MINUS_SRC_ALPHA);
  274. }
  275. _node = node;
  276. }
  277. void Form::update(float elapsedTime)
  278. {
  279. if (true)//isDirty())
  280. {
  281. update(NULL, Vector2::zero());
  282. // Cache themed attributes for performance.
  283. _skin = getSkin(_state);
  284. _opacity = getOpacity(_state);
  285. GP_ASSERT(_layout);
  286. if (_scroll != SCROLL_NONE)
  287. {
  288. updateScroll();
  289. }
  290. else
  291. {
  292. _layout->update(this, Vector2::zero());
  293. }
  294. }
  295. }
  296. void Form::update(const Control* container, const Vector2& offset)
  297. {
  298. // Store previous absolute bounds
  299. Rectangle oldAbsoluteClipBounds = _absoluteClipBounds;
  300. _layout->align(this, NULL);
  301. Container::update(container, offset);
  302. if (_absoluteClipBounds.width != oldAbsoluteClipBounds.width || _absoluteClipBounds.height != oldAbsoluteClipBounds.height)
  303. {
  304. updateFrameBuffer();
  305. }
  306. }
  307. void Form::draw()
  308. {
  309. if (!_visible || !_frameBuffer)
  310. return;
  311. // The first time a form is drawn, its contents are rendered into a framebuffer.
  312. // The framebuffer will only be drawn into again when the contents of the form change.
  313. // If this form has a node then it's a 3D form and the framebuffer will be used
  314. // to texture a quad. The quad will be given the same dimensions as the form and
  315. // must be transformed appropriately by the user, unless they call setQuad() themselves.
  316. // On the other hand, if this form has not been set on a node, SpriteBatch will be used
  317. // to render the contents of the framebuffer directly to the display.
  318. // Check whether this form has changed since the last call to draw() and if so, render into the framebuffer.
  319. if (true)//isDirty())
  320. {
  321. FrameBuffer* previousFrameBuffer = _frameBuffer->bind();
  322. Game* game = Game::getInstance();
  323. Rectangle prevViewport = game->getViewport();
  324. game->setViewport(Rectangle(0, 0, _absoluteClipBounds.width, _absoluteClipBounds.height));
  325. GP_ASSERT(_theme);
  326. _theme->setProjectionMatrix(_projectionMatrix);
  327. // By setting needsClear to true here, an optimization meant to clear and redraw only areas of the form
  328. // that have changed is disabled. Currently, repositioning controls can result in areas of the screen being cleared
  329. // after another control has been drawn there. This should probably be done in two passes -- one to clear areas where
  330. // dirty controls were last frame, and another to draw them where they are now.
  331. Container::draw(_theme->getSpriteBatch(), _absoluteClipBounds, /*_skin != NULL*/ true, false, _absoluteClipBounds.height);
  332. // Restore the previous game viewport.
  333. game->setViewport(prevViewport);
  334. // Rebind the previous framebuffer and game viewport.
  335. previousFrameBuffer->bind();
  336. }
  337. // Draw either with a 3D quad or sprite batch.
  338. if (_node)
  339. {
  340. // If we have the node set, then draw a 3D quad model.
  341. _nodeQuad->draw();
  342. }
  343. else
  344. {
  345. // Otherwise we draw the framebuffer in ortho space with a spritebatch.
  346. _spriteBatch->start();
  347. _spriteBatch->draw(_bounds.x, _bounds.y, 0, _bounds.width, _bounds.height, 0, _v1, _u2, 0, Vector4::one());
  348. _spriteBatch->finish();
  349. }
  350. }
  351. const char* Form::getType() const
  352. {
  353. return "form";
  354. }
  355. void Form::updateInternal(float elapsedTime)
  356. {
  357. size_t size = __forms.size();
  358. for (size_t i = 0; i < size; ++i)
  359. {
  360. Form* form = __forms[i];
  361. GP_ASSERT(form);
  362. if (form->isEnabled() && form->isVisible())
  363. {
  364. form->update(elapsedTime);
  365. }
  366. }
  367. }
  368. static bool shouldPropagateTouchEvent(Control::State state, Touch::TouchEvent evt, const Rectangle& bounds, int x, int y)
  369. {
  370. return (state != Control::NORMAL ||
  371. (evt == Touch::TOUCH_PRESS &&
  372. x >= bounds.x &&
  373. x <= bounds.x + bounds.width &&
  374. y >= bounds.y &&
  375. y <= bounds.y + bounds.height));
  376. }
  377. bool Form::touchEventInternal(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  378. {
  379. // Check for a collision with each Form in __forms.
  380. // Pass the event on.
  381. size_t size = __forms.size();
  382. for (size_t i = 0; i < size; ++i)
  383. {
  384. Form* form = __forms[i];
  385. GP_ASSERT(form);
  386. if (form->isEnabled() && form->isVisible())
  387. {
  388. if (form->_node)
  389. {
  390. Vector3 point;
  391. if (form->projectPoint(x, y, &point))
  392. {
  393. const Rectangle& bounds = form->getBounds();
  394. if (shouldPropagateTouchEvent(form->getState(), evt, bounds, point.x, point.y))
  395. {
  396. if (form->touchEvent(evt, point.x - bounds.x, bounds.height - point.y - bounds.y, contactIndex))
  397. return true;
  398. }
  399. }
  400. }
  401. else
  402. {
  403. // Simply compare with the form's bounds.
  404. const Rectangle& bounds = form->getBounds();
  405. if (shouldPropagateTouchEvent(form->getState(), evt, bounds, x, y))
  406. {
  407. // Pass on the event's position relative to the form.
  408. if (form->touchEvent(evt, x - bounds.x, y - bounds.y, contactIndex))
  409. return true;
  410. }
  411. }
  412. }
  413. }
  414. return false;
  415. }
  416. bool Form::keyEventInternal(Keyboard::KeyEvent evt, int key)
  417. {
  418. size_t size = __forms.size();
  419. for (size_t i = 0; i < size; ++i)
  420. {
  421. Form* form = __forms[i];
  422. GP_ASSERT(form);
  423. if (form->isEnabled() && form->isVisible() && form->hasFocus() && !form->_isGamepad)
  424. {
  425. if (form->keyEvent(evt, key))
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. static bool shouldPropagateMouseEvent(Control::State state, Mouse::MouseEvent evt, const Rectangle& bounds, int x, int y)
  432. {
  433. return (state != Control::NORMAL ||
  434. ((evt == Mouse::MOUSE_PRESS_LEFT_BUTTON ||
  435. evt == Mouse::MOUSE_PRESS_MIDDLE_BUTTON ||
  436. evt == Mouse::MOUSE_PRESS_RIGHT_BUTTON ||
  437. evt == Mouse::MOUSE_MOVE ||
  438. evt == Mouse::MOUSE_WHEEL) &&
  439. x >= bounds.x &&
  440. x <= bounds.x + bounds.width &&
  441. y >= bounds.y &&
  442. y <= bounds.y + bounds.height));
  443. }
  444. bool Form::mouseEventInternal(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  445. {
  446. // Do not process mouse input when mouse is captured
  447. if (Game::getInstance()->isMouseCaptured())
  448. return false;
  449. for (size_t i = 0; i < __forms.size(); ++i)
  450. {
  451. Form* form = __forms[i];
  452. GP_ASSERT(form);
  453. if (form->isEnabled() && form->isVisible())
  454. {
  455. if (form->_node)
  456. {
  457. Vector3 point;
  458. if (form->projectPoint(x, y, &point))
  459. {
  460. const Rectangle& bounds = form->getBounds();
  461. if (shouldPropagateMouseEvent(form->getState(), evt, bounds, point.x, point.y))
  462. {
  463. if (form->mouseEvent(evt, point.x - bounds.x, bounds.height - point.y - bounds.y, wheelDelta))
  464. return true;
  465. }
  466. }
  467. }
  468. else
  469. {
  470. // Simply compare with the form's bounds.
  471. const Rectangle& bounds = form->getBounds();
  472. if (shouldPropagateMouseEvent(form->getState(), evt, bounds, x, y))
  473. {
  474. // Pass on the event's position relative to the form.
  475. if (form->mouseEvent(evt, x - bounds.x, y - bounds.y, wheelDelta))
  476. return true;
  477. }
  478. }
  479. }
  480. }
  481. return false;
  482. }
  483. void Form::gamepadEventInternal(Gamepad::GamepadEvent evt, Gamepad* gamepad, unsigned int analogIndex)
  484. {
  485. for (size_t i = 0; i < __forms.size(); ++i)
  486. {
  487. Form* form = __forms[i];
  488. GP_ASSERT(form);
  489. if (form->isEnabled() && form->isVisible() && form->hasFocus())
  490. {
  491. if (form->gamepadEvent(evt, gamepad, analogIndex))
  492. return;
  493. }
  494. }
  495. }
  496. void Form::resizeEventInternal(unsigned int width, unsigned int height)
  497. {
  498. for (size_t i = 0; i < __forms.size(); ++i)
  499. {
  500. Form* form = __forms[i];
  501. if (form)
  502. {
  503. if (form->_spriteBatch)
  504. {
  505. // Update viewport projection matrix
  506. Matrix viewportProjection;
  507. Matrix::createOrthographicOffCenter(0, Game::getInstance()->getViewport().width, Game::getInstance()->getViewport().height, 0, 0, 1, &viewportProjection);
  508. form->_spriteBatch->setProjectionMatrix(viewportProjection);
  509. }
  510. // Dirty the form
  511. form->_dirty = true;
  512. }
  513. }
  514. }
  515. bool Form::projectPoint(int x, int y, Vector3* point)
  516. {
  517. Scene* scene = _node->getScene();
  518. Camera* camera;
  519. if (scene && (camera = scene->getActiveCamera()))
  520. {
  521. // Get info about the form's position.
  522. Matrix m = _node->getWorldMatrix();
  523. Vector3 pointOnPlane(0, 0, 0);
  524. m.transformPoint(&pointOnPlane);
  525. // Unproject point into world space.
  526. Ray ray;
  527. camera->pickRay(Game::getInstance()->getViewport(), x, y, &ray);
  528. // Find the quad's plane. We know its normal is the quad's forward vector.
  529. Vector3 normal = _node->getForwardVectorWorld().normalize();
  530. // To get the plane's distance from the origin, we project a point on the
  531. // plane onto the plane's normal vector.
  532. const float distance = fabs(Vector3::dot(pointOnPlane, normal));
  533. Plane plane(normal, -distance);
  534. // Check for collision with plane.
  535. float collisionDistance = ray.intersects(plane);
  536. if (collisionDistance != Ray::INTERSECTS_NONE)
  537. {
  538. // Multiply the ray's direction vector by collision distance and add that to the ray's origin.
  539. point->set(ray.getOrigin() + collisionDistance*ray.getDirection());
  540. // Project this point into the plane.
  541. m.invert();
  542. m.transformPoint(point);
  543. return true;
  544. }
  545. }
  546. return false;
  547. }
  548. unsigned int Form::nextPowerOfTwo(unsigned int v)
  549. {
  550. if (!((v & (v - 1)) == 0))
  551. {
  552. v--;
  553. v |= v >> 1;
  554. v |= v >> 2;
  555. v |= v >> 4;
  556. v |= v >> 8;
  557. v |= v >> 16;
  558. return v + 1;
  559. }
  560. else
  561. {
  562. return v;
  563. }
  564. }
  565. }