PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/src/threed/painting/qglpainter.cpp

https://bitbucket.org/manctl/qt3d
C++ | 2366 lines | 1308 code | 148 blank | 910 comment | 222 complexity | ec43ac14b87db2d542b2b8f4bf4379f7 MD5 | raw file
Possible License(s): CC-BY-SA-4.0, LGPL-2.1, GPL-3.0, AGPL-3.0, LGPL-3.0
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/
  5. **
  6. ** This file is part of the Qt3D module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** GNU Lesser General Public License Usage
  10. ** This file may be used under the terms of the GNU Lesser General Public
  11. ** License version 2.1 as published by the Free Software Foundation and
  12. ** appearing in the file LICENSE.LGPL included in the packaging of this
  13. ** file. Please review the following information to ensure the GNU Lesser
  14. ** General Public License version 2.1 requirements will be met:
  15. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  16. **
  17. ** In addition, as a special exception, Nokia gives you certain additional
  18. ** rights. These rights are described in the Nokia Qt LGPL Exception
  19. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  20. **
  21. ** GNU General Public License Usage
  22. ** Alternatively, this file may be used under the terms of the GNU General
  23. ** Public License version 3.0 as published by the Free Software Foundation
  24. ** and appearing in the file LICENSE.GPL included in the packaging of this
  25. ** file. Please review the following information to ensure the GNU General
  26. ** Public License version 3.0 requirements will be met:
  27. ** http://www.gnu.org/copyleft/gpl.html.
  28. **
  29. ** Other Usage
  30. ** Alternatively, this file may be used in accordance with the terms and
  31. ** conditions contained in a signed written agreement between you and Nokia.
  32. **
  33. **
  34. **
  35. **
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. #include "qglpainter.h"
  42. #include "qglpainter_p.h"
  43. #include "qglabstracteffect.h"
  44. #include "qglext_p.h"
  45. #include <QOpenGLContext>
  46. #include <QOpenGLShaderProgram>
  47. #include <QOpenGLFramebufferObject>
  48. #include <QPainter>
  49. #include <QPaintEngine>
  50. #include <QVarLengthArray>
  51. #include <QMap>
  52. #include <QDebug>
  53. #if !defined(QT_NO_THREAD)
  54. #include <QThreadStorage>
  55. #include <QThread>
  56. #endif
  57. #include "qglflatcoloreffect_p.h"
  58. #include "qglflattextureeffect_p.h"
  59. #include "qgllitmaterialeffect_p.h"
  60. #include "qgllittextureeffect_p.h"
  61. #include "qglpickcolors_p.h"
  62. #include "qgltexture2d.h"
  63. #include "qgltexturecube.h"
  64. #include "qgeometrydata.h"
  65. #include "qglvertexbundle_p.h"
  66. #include "qmatrix4x4stack_p.h"
  67. #include "qglwindowsurface.h"
  68. #include "qglpaintersurface_p.h"
  69. #undef glActiveTexture
  70. QT_BEGIN_NAMESPACE
  71. /*!
  72. \class QGLPainter
  73. \brief The QGLPainter class provides portable API's for rendering into a GL context.
  74. \since 4.8
  75. \ingroup qt3d
  76. \ingroup qt3d::painting
  77. TBD - lots of TBD
  78. All QGLPainter instances on a context share the same context state:
  79. matrices, effects, vertex attributes, etc. For example, calling
  80. ortho() on one QGLPainter instance for a context will alter the
  81. projectionMatrix() as seen by the other QGLPainter instances.
  82. */
  83. /*!
  84. \enum QGLPainter::Update
  85. This enum defines the values that were changed since the last QGLPainter::update().
  86. \value UpdateColor The color has been updated.
  87. \value UpdateModelViewMatrix The modelview matrix has been updated.
  88. \value UpdateProjectionMatrix The projection matrix has been updated.
  89. \value UpdateMatrices The combination of UpdateModelViewMatrix and
  90. UpdateProjectionMatrix.
  91. \value UpdateLights The lights have been updated.
  92. \value UpdateMaterials The material parameters have been updated.
  93. \value UpdateViewport The viewport needs to be updated because the
  94. drawing surface has changed.
  95. \value UpdateAll All values have been updated. This is specified
  96. when an effect is activated.
  97. */
  98. #define QGLPAINTER_CHECK_PRIVATE() \
  99. Q_ASSERT_X(d, "QGLPainter", "begin() has not been called or it failed")
  100. QGLPainterPrivate::QGLPainterPrivate()
  101. : ref(1),
  102. badShaderCount(0),
  103. eye(QGL::NoEye),
  104. lightModel(0),
  105. defaultLightModel(0),
  106. defaultLight(0),
  107. frontMaterial(0),
  108. backMaterial(0),
  109. defaultMaterial(0),
  110. frontColorMaterial(0),
  111. backColorMaterial(0),
  112. viewingCube(QVector3D(-1, -1, -1), QVector3D(1, 1, 1)),
  113. color(255, 255, 255, 255),
  114. updates(QGLPainter::UpdateAll),
  115. pick(0),
  116. boundVertexBuffer(0),
  117. boundIndexBuffer(0),
  118. renderSequencer(0),
  119. isFixedFunction(true) // Updated by QGLPainter::begin()
  120. {
  121. context = 0;
  122. effect = 0;
  123. userEffect = 0;
  124. standardEffect = QGL::FlatColor;
  125. memset(stdeffects, 0, sizeof(stdeffects));
  126. }
  127. QGLPainterPrivate::~QGLPainterPrivate()
  128. {
  129. delete defaultLightModel;
  130. delete defaultLight;
  131. delete defaultMaterial;
  132. delete frontColorMaterial;
  133. delete backColorMaterial;
  134. for (int effect = 0; effect < QGL_MAX_STD_EFFECTS; ++effect)
  135. delete stdeffects[effect];
  136. delete pick;
  137. qDeleteAll(cachedPrograms);
  138. delete renderSequencer;
  139. }
  140. QGLPainterPickPrivate::QGLPainterPickPrivate()
  141. {
  142. isPicking = false;
  143. objectPickId = -1;
  144. pickColorIndex = -1;
  145. pickColor = 0;
  146. defaultPickEffect = new QGLFlatColorEffect();
  147. }
  148. QGLPainterPickPrivate::~QGLPainterPickPrivate()
  149. {
  150. delete defaultPickEffect;
  151. }
  152. #if !defined(QT_NO_THREAD)
  153. // QOpenGLContext's are thread-specific, so QGLPainterPrivateCache should be too.
  154. typedef QThreadStorage<QGLPainterPrivateCache *> QGLPainterPrivateStorage;
  155. Q_GLOBAL_STATIC(QGLPainterPrivateStorage, painterPrivateStorage)
  156. static QGLPainterPrivateCache *painterPrivateCache()
  157. {
  158. QGLPainterPrivateCache *cache = painterPrivateStorage()->localData();
  159. if (!cache) {
  160. cache = new QGLPainterPrivateCache();
  161. painterPrivateStorage()->setLocalData(cache);
  162. }
  163. return cache;
  164. }
  165. #else
  166. Q_GLOBAL_STATIC(QGLPainterPrivateCache, painterPrivateCache)
  167. #endif
  168. QGLPainterPrivateCache::QGLPainterPrivateCache()
  169. {
  170. }
  171. QGLPainterPrivateCache::~QGLPainterPrivateCache()
  172. {
  173. }
  174. QGLPainterPrivate *QGLPainterPrivateCache::fromContext(QOpenGLContext *context)
  175. {
  176. QGLPainterPrivate *priv = cache.value(context, 0);
  177. if (priv)
  178. return priv;
  179. #ifndef QT_NO_THREAD
  180. Q_ASSERT_X(context->thread() == QThread::currentThread(),
  181. Q_FUNC_INFO,
  182. "Attempt to fetch painter state for context outside contexts thread");
  183. #endif
  184. // since we assert this is the same thread then this is bound to be a direct
  185. // connection, not a queued (asynchronous) connection
  186. connect(context, SIGNAL(destroyed()), this, SLOT(contextDestroyed()));
  187. priv = new QGLPainterPrivate();
  188. priv->context = context;
  189. cache.insert(context, priv);
  190. return priv;
  191. }
  192. QGLPainterPrivateCache *QGLPainterPrivateCache::instance()
  193. {
  194. return painterPrivateCache();
  195. }
  196. void QGLPainterPrivateCache::contextDestroyed()
  197. {
  198. QOpenGLContext *context = qobject_cast<QOpenGLContext *>(sender());
  199. QGLPainterPrivate *priv = cache.value(context, 0);
  200. if (priv) {
  201. priv->context = 0;
  202. cache.remove(context);
  203. if (!priv->ref.deref())
  204. delete priv;
  205. }
  206. emit destroyedContext(context);
  207. }
  208. /*!
  209. Constructs a new GL painter. Call begin() to attach the
  210. painter to a GL context.
  211. \sa begin()
  212. */
  213. QGLPainter::QGLPainter()
  214. : d_ptr(0)
  215. {
  216. }
  217. /*!
  218. Constructs a new GL painter and attaches it to \a context.
  219. It is not necessary to call begin() after construction.
  220. \sa begin()
  221. */
  222. QGLPainter::QGLPainter(QOpenGLContext *context)
  223. : d_ptr(0)
  224. {
  225. begin(context);
  226. }
  227. /*!
  228. Constructs a new GL painter and attaches it to the GL
  229. context associated with \a window. It is not necessary to
  230. call begin() after construction.
  231. \sa begin(), isActive()
  232. */
  233. QGLPainter::QGLPainter(QWindow *window)
  234. : d_ptr(0)
  235. {
  236. begin(window);
  237. }
  238. /*!
  239. Constructs a new GL painter and attaches it to the GL context associated
  240. with \a painter. It is assumed that \a painter is the currently
  241. active painter and that it is associated with the current GL context.
  242. If \a painter is not using an OpenGL paint engine, then isActive()
  243. will return false; true otherwise.
  244. This constructor is typically used when mixing regular Qt painting
  245. operations and GL painting operations on a widget that is being
  246. drawn using the OpenGL graphics system.
  247. \sa begin(), isActive()
  248. */
  249. QGLPainter::QGLPainter(QPainter *painter)
  250. : d_ptr(0)
  251. {
  252. begin(painter);
  253. }
  254. /*!
  255. Constructs a new GL painter and attaches it to the GL context associated
  256. with \a surface.
  257. \sa begin(), isActive()
  258. */
  259. QGLPainter::QGLPainter(QGLAbstractSurface *surface)
  260. : d_ptr(0)
  261. {
  262. begin(surface);
  263. }
  264. /*!
  265. Destroys this GL painter.
  266. */
  267. QGLPainter::~QGLPainter()
  268. {
  269. end();
  270. }
  271. /*!
  272. Begins painting on the current GL context. Returns false
  273. if there is no GL context current.
  274. \sa end()
  275. */
  276. bool QGLPainter::begin()
  277. {
  278. return begin(QOpenGLContext::currentContext());
  279. }
  280. /*!
  281. Begins painting on \a context. If painting was already in progress,
  282. then this function will call end() first. The \a context will be
  283. made current if it is not already current.
  284. Returns true if painting can begin; false otherwise.
  285. All QGLPainter instances on a context share the same context state:
  286. matrices, the effect(), vertex attributes, etc. For example,
  287. calling ortho() on one QGLPainter instance for a context will
  288. alter the projectionMatrix() as seen by the other QGLPainter instances.
  289. \sa end(), isActive()
  290. */
  291. bool QGLPainter::begin(QOpenGLContext *context)
  292. {
  293. if (!context)
  294. return false;
  295. end();
  296. return begin(context, QGLAbstractSurface::createSurfaceForContext(context));
  297. }
  298. /*!
  299. \internal
  300. */
  301. bool QGLPainter::begin
  302. (QOpenGLContext *context, QGLAbstractSurface *surface,
  303. bool destroySurface)
  304. {
  305. // If we don't have a context specified, then use the one
  306. // that the surface just made current.
  307. if (!context)
  308. context = QOpenGLContext::currentContext();
  309. if (!context)
  310. {
  311. qWarning() << "##### Attempt to begin painter with no GL context!";
  312. return false;
  313. }
  314. // Initialize the QOpenGLFunctions parent class.
  315. initializeGLFunctions();
  316. // Determine if the OpenGL implementation is fixed-function or not.
  317. bool isFixedFunction = !hasOpenGLFeature(QOpenGLFunctions::Shaders);
  318. if (!isFixedFunction)
  319. isFixedFunction = !QOpenGLShaderProgram::hasOpenGLShaderPrograms();
  320. if (!isFixedFunction)
  321. {
  322. QOpenGLContext *ctx = QOpenGLContext::currentContext();
  323. QFunctionPointer res = ctx->getProcAddress("glCreateShader");
  324. if (!res)
  325. {
  326. res = ctx->getProcAddress("glCreateShaderObject");
  327. if (!res)
  328. {
  329. res = ctx->getProcAddress("glCreateShaderObjectARB");
  330. }
  331. }
  332. if (!res)
  333. isFixedFunction = !res;
  334. }
  335. // Find the QGLPainterPrivate for the context, or create a new one.
  336. d_ptr = painterPrivateCache()->fromContext(context);
  337. d_ptr->ref.ref();
  338. d_ptr->isFixedFunction = isFixedFunction;
  339. if (d_ptr->renderSequencer)
  340. {
  341. d_ptr->renderSequencer->reset();
  342. d_ptr->renderSequencer->setPainter(this);
  343. }
  344. // Activate the main surface for the context.
  345. QGLAbstractSurface *prevSurface;
  346. if (d_ptr->surfaceStack.isEmpty()) {
  347. prevSurface = 0;
  348. } else {
  349. // We are starting a nested begin()/end() scope, so switch
  350. // to the new main surface rather than activate from scratch.
  351. prevSurface = d_ptr->surfaceStack.last().surface;
  352. prevSurface->deactivate(surface);
  353. }
  354. if (!surface->activate(prevSurface)) {
  355. if (prevSurface)
  356. prevSurface->activate(surface);
  357. if (destroySurface)
  358. delete surface;
  359. if (!d_ptr->ref.deref())
  360. delete d_ptr;
  361. d_ptr = 0;
  362. return false;
  363. }
  364. // Push a main surface descriptor onto the surface stack.
  365. QGLPainterSurfaceInfo psurf;
  366. psurf.surface = surface;
  367. psurf.destroySurface = destroySurface;
  368. psurf.mainSurface = true;
  369. d_ptr->surfaceStack.append(psurf);
  370. // Force the matrices to be updated the first time we use them.
  371. d_ptr->modelViewMatrix.setDirty(true);
  372. d_ptr->projectionMatrix.setDirty(true);
  373. return true;
  374. }
  375. /*!
  376. Begins GL painting on \a widget. Returns false if \a widget is null.
  377. \sa end()
  378. */
  379. bool QGLPainter::begin(QWindow *window)
  380. {
  381. bool result = false;
  382. if (window)
  383. {
  384. end();
  385. result = begin(0, new QGLWindowSurface(window));
  386. }
  387. return result;
  388. }
  389. /*!
  390. Begins painting on the GL context associated with \a painter.
  391. Returns false if \a painter is not using an OpenGL paint engine.
  392. It is assumed that \a painter is the currently active painter
  393. and that it is associated with the current GL context.
  394. This function is typically used when mixing regular Qt painting
  395. operations and GL painting operations on a widget that is being
  396. drawn using the OpenGL graphics system.
  397. \sa end()
  398. */
  399. bool QGLPainter::begin(QPainter *painter)
  400. {
  401. // Validate that the painting is OpenGL-based.
  402. if (!painter)
  403. return false;
  404. QPaintEngine *engine = painter->paintEngine();
  405. if (!engine)
  406. return false;
  407. if (engine->type() != QPaintEngine::OpenGL &&
  408. engine->type() != QPaintEngine::OpenGL2)
  409. return false;
  410. // Begin GL painting operations.
  411. return begin(0, new QGLPainterSurface(painter));
  412. }
  413. /*!
  414. Begins painting to \a surface. Returns false if \a surface is
  415. null or could not be activated.
  416. \sa end(), QGLAbstractSurface::activate()
  417. */
  418. bool QGLPainter::begin(QGLAbstractSurface *surface)
  419. {
  420. if (!surface)
  421. return false;
  422. end();
  423. return begin(0, surface, false);
  424. }
  425. /*!
  426. Ends GL painting. Returns true if painting was ended successfully;
  427. false if this painter was not bound to a GL context.
  428. The GL context that was bound to this painter will not have
  429. QOpenGLContext::doneCurrent() called on it. It is the responsibility
  430. of the caller to terminate context operations.
  431. The effect() will be left active in the GL context and will be
  432. assumed to still be active the next time begin() is called.
  433. If this assumption doesn't apply, then call disableEffect()
  434. to disable the effect before calling end().
  435. This function will pop all surfaces from the surface stack,
  436. and return currentSurface() to null (the default drawing surface).
  437. \sa begin(), isActive(), disableEffect()
  438. */
  439. bool QGLPainter::end()
  440. {
  441. Q_D(QGLPainter);
  442. if (!d)
  443. return false;
  444. // Unbind the current vertex and index buffers.
  445. if (d->boundVertexBuffer) {
  446. QOpenGLBuffer::release(QOpenGLBuffer::VertexBuffer);
  447. d->boundVertexBuffer = 0;
  448. }
  449. if (d->boundIndexBuffer) {
  450. QOpenGLBuffer::release(QOpenGLBuffer::IndexBuffer);
  451. d->boundIndexBuffer = 0;
  452. }
  453. // Pop surfaces from the surface stack until we reach a
  454. // main surface. Then deactivate the main surface.
  455. int size = d->surfaceStack.size();
  456. while (size > 0) {
  457. --size;
  458. QGLPainterSurfaceInfo &surf = d->surfaceStack[size];
  459. if (surf.mainSurface) {
  460. if (size > 0) {
  461. // There are still other surfaces on the stack, probably
  462. // because we are within a nested begin()/end() scope.
  463. // Re-activate the next surface down in the outer scope.
  464. QGLPainterSurfaceInfo &nextSurf = d->surfaceStack[size - 1];
  465. surf.surface->switchTo(nextSurf.surface);
  466. } else {
  467. // Last surface on the stack, so deactivate it permanently.
  468. surf.surface->deactivate();
  469. }
  470. if (surf.destroySurface)
  471. delete surf.surface;
  472. break;
  473. } else if (size > 0) {
  474. surf.surface->deactivate(d->surfaceStack[size - 1].surface);
  475. }
  476. }
  477. d->surfaceStack.resize(size);
  478. // Force a viewport update if we are within a nested begin()/end().
  479. d->updates |= UpdateViewport;
  480. // Destroy the QGLPainterPrivate if this is the last reference.
  481. if (!d->ref.deref())
  482. delete d;
  483. d_ptr = 0;
  484. return true;
  485. }
  486. /*!
  487. Returns true if this painter is currently bound to a GL context;
  488. false otherwise.
  489. \sa begin(), end()
  490. */
  491. bool QGLPainter::isActive() const
  492. {
  493. return (d_ptr != 0 && d_ptr->context != 0);
  494. }
  495. /*!
  496. Returns the GL context that is bound to this painter, or null
  497. if it is not currently bound.
  498. */
  499. QOpenGLContext *QGLPainter::context() const
  500. {
  501. if (d_ptr)
  502. return d_ptr->context;
  503. else
  504. return 0;
  505. }
  506. /*!
  507. Returns true if the underlying OpenGL implementation is OpenGL 1.x
  508. or OpenGL/ES 1.x and only supports fixed-function OpenGL operations.
  509. Returns false if the underlying OpenGL implementation is using
  510. GLSL or GLSL/ES shaders.
  511. If this function returns false, then the built-in effects will
  512. use shaders and QGLPainter will not update the fixed-function
  513. matrices in the OpenGL context when update() is called.
  514. User-supplied effects will need to use shaders also or update
  515. the fixed-function matrices themselves or call updateFixedFunction().
  516. \sa update(), updateFixedFunction()
  517. */
  518. bool QGLPainter::isFixedFunction() const
  519. {
  520. #if defined(QT_OPENGL_ES_2)
  521. return false;
  522. #else
  523. Q_D(const QGLPainter);
  524. if (d)
  525. return d->isFixedFunction;
  526. else
  527. return true;
  528. #endif
  529. }
  530. /*!
  531. Sets the \a color to use to clear the color buffer when \c{glClear()}
  532. is called.
  533. */
  534. void QGLPainter::setClearColor(const QColor& color)
  535. {
  536. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  537. }
  538. /*!
  539. Sets the scissor \a rect for the current drawing surface
  540. to use when \c{GL_SCISSOR_TEST} is enabled. If \a rect is empty,
  541. then the scissor will be set to clip away all drawing.
  542. Note that \a rect is in Qt co-ordinates with the origin
  543. at the top-left of the drawing surface's viewport rectangle.
  544. If the currentSurface() is an instance of QGLSubsurface,
  545. then \a rect will be adjusted relative to the subsurface's position.
  546. \sa currentSurface(), QGLAbstractSurface::viewportGL()
  547. */
  548. void QGLPainter::setScissor(const QRect& rect)
  549. {
  550. if (!rect.isEmpty()) {
  551. // Adjust the rectangle by the position of the surface viewport.
  552. QGLAbstractSurface *surface = currentSurface();
  553. QRect viewport = surface->viewportGL();
  554. QRect r(viewport.x() + rect.x(),
  555. viewport.y() + viewport.height() - (rect.y() + rect.height()),
  556. rect.width(), rect.height());
  557. if (!r.isEmpty())
  558. glScissor(r.x(), r.y(), r.width(), r.height());
  559. else
  560. glScissor(0, 0, 0, 0);
  561. } else {
  562. glScissor(0, 0, 0, 0);
  563. }
  564. }
  565. /*!
  566. Returns a reference to the projection matrix stack.
  567. It is recommended that setCamera() be used to set the projection
  568. matrix at the beginning of a scene rendering pass so that the
  569. eye position can be adjusted for stereo.
  570. \sa modelViewMatrix(), combinedMatrix(), setCamera()
  571. */
  572. QMatrix4x4Stack& QGLPainter::projectionMatrix()
  573. {
  574. Q_D(QGLPainter);
  575. QGLPAINTER_CHECK_PRIVATE();
  576. return d->projectionMatrix;
  577. }
  578. /*!
  579. Returns a reference to the modelview matrix stack.
  580. \sa projectionMatrix(), combinedMatrix(), normalMatrix(), setCamera()
  581. \sa worldMatrix()
  582. */
  583. QMatrix4x4Stack& QGLPainter::modelViewMatrix()
  584. {
  585. Q_D(QGLPainter);
  586. QGLPAINTER_CHECK_PRIVATE();
  587. return d->modelViewMatrix;
  588. }
  589. /*!
  590. \fn QMatrix4x4 QGLPainter::combinedMatrix() const
  591. Returns the result of multiplying the projectionMatrix()
  592. and the modelViewMatrix(). This combined matrix value is
  593. useful for setting uniform matrix values on shader programs.
  594. Calling this function is more efficient than calling
  595. projectionMatrix() and modelViewMatrix() separately and
  596. multiplying the return values.
  597. \sa projectionMatrix(), modelViewMatrix(), normalMatrix()
  598. */
  599. QMatrix4x4 QGLPainter::combinedMatrix() const
  600. {
  601. const QGLPainterPrivate *d = d_func();
  602. if (!d)
  603. return QMatrix4x4();
  604. const QMatrix4x4StackPrivate *proj = d->projectionMatrix.d_func();
  605. const QMatrix4x4StackPrivate *mv = d->modelViewMatrix.d_func();
  606. return proj->matrix * mv->matrix;
  607. }
  608. // Inverting the eye transformation will often result in values like
  609. // 1.5e-15 in the world matrix. Clamp these to zero to make worldMatrix()
  610. // more stable when removing the eye component of the modelViewMatrix().
  611. static inline qreal qt_gl_stablize_value(qreal value)
  612. {
  613. return (qAbs(value) >= 0.00001f) ? value : 0.0f;
  614. }
  615. static inline QMatrix4x4 qt_gl_stablize_matrix(const QMatrix4x4 &m)
  616. {
  617. return QMatrix4x4(qt_gl_stablize_value(m(0, 0)),
  618. qt_gl_stablize_value(m(0, 1)),
  619. qt_gl_stablize_value(m(0, 2)),
  620. qt_gl_stablize_value(m(0, 3)),
  621. qt_gl_stablize_value(m(1, 0)),
  622. qt_gl_stablize_value(m(1, 1)),
  623. qt_gl_stablize_value(m(1, 2)),
  624. qt_gl_stablize_value(m(1, 3)),
  625. qt_gl_stablize_value(m(2, 0)),
  626. qt_gl_stablize_value(m(2, 1)),
  627. qt_gl_stablize_value(m(2, 2)),
  628. qt_gl_stablize_value(m(2, 3)),
  629. qt_gl_stablize_value(m(3, 0)),
  630. qt_gl_stablize_value(m(3, 1)),
  631. qt_gl_stablize_value(m(3, 2)),
  632. qt_gl_stablize_value(m(3, 3)));
  633. }
  634. /*!
  635. Returns the world matrix, which is the modelViewMatrix() without
  636. the eye transformation that was set in the previous call to
  637. setCamera().
  638. In the following example, the \c{world} variable will be set to the
  639. translation and scale component of the modelview transformation,
  640. without the "look at" component from the camera:
  641. \code
  642. painter.setCamera(camera);
  643. painter.modelViewMatrix().translate(0.0f, 5.0f, 0.0f);
  644. painter.modelViewMatrix().scale(1.5f);
  645. QMatrix4x4 world = painter.worldMatrix();
  646. \endcode
  647. Note: the world matrix is determined by multiplying the inverse of
  648. the camera's look at component with the current modelview matrix.
  649. Thus, the result may not be precisely the same as constructing a
  650. matrix from translate and scale operations starting with the identity.
  651. \sa modelViewMatrix(), setCamera()
  652. */
  653. QMatrix4x4 QGLPainter::worldMatrix() const
  654. {
  655. Q_D(const QGLPainter);
  656. QGLPAINTER_CHECK_PRIVATE();
  657. return qt_gl_stablize_matrix
  658. (d->inverseEyeMatrix * d->modelViewMatrix.top());
  659. }
  660. /*!
  661. \fn QMatrix3x3 QGLPainter::normalMatrix() const
  662. Returns the normal matrix corresponding to modelViewMatrix().
  663. The normal matrix is the transpose of the inverse of the top-left
  664. 3x3 part of the 4x4 modelview matrix. If the 3x3 sub-matrix is not
  665. invertible, this function returns the identity.
  666. \sa modelViewMatrix(), combinedMatrix()
  667. */
  668. QMatrix3x3 QGLPainter::normalMatrix() const
  669. {
  670. const QGLPainterPrivate *d = d_func();
  671. if (!d)
  672. return QMatrix3x3();
  673. const QMatrix4x4StackPrivate *mv = d->modelViewMatrix.d_func();
  674. return mv->matrix.normalMatrix();
  675. }
  676. /*!
  677. Returns the camera eye that is currently being used for stereo
  678. rendering. The default is QGL::NoEye.
  679. The eye is used to adjust the camera position by a small amount
  680. when setCamera() is called.
  681. \sa setEye(), setCamera()
  682. */
  683. QGL::Eye QGLPainter::eye() const
  684. {
  685. Q_D(const QGLPainter);
  686. QGLPAINTER_CHECK_PRIVATE();
  687. return d->eye;
  688. }
  689. /*!
  690. Sets the camera \a eye that is currently being used for stereo
  691. rendering.
  692. The \a eye is used to adjust the camera position by a small amount
  693. when setCamera() is called.
  694. \sa eye(), setCamera()
  695. */
  696. void QGLPainter::setEye(QGL::Eye eye)
  697. {
  698. Q_D(QGLPainter);
  699. QGLPAINTER_CHECK_PRIVATE();
  700. d->eye = eye;
  701. }
  702. /*!
  703. Sets the modelViewMatrix() and projectionMatrix() to the view
  704. defined by \a camera. If eye() is not QGL::NoEye, then the view
  705. will be adjusted for the camera's eye separation.
  706. This function is typically called at the beginning of a scene rendering
  707. pass to initialize the modelview and projection matrices.
  708. Note that this does not cause the painter to take ownership of the camera
  709. and it does not save the pointer value. The \a camera may be safely
  710. deleted after calling this function.
  711. \sa eye(), modelViewMatrix(), projectionMatrix(), worldMatrix()
  712. */
  713. void QGLPainter::setCamera(const QGLCamera *camera)
  714. {
  715. Q_ASSERT(camera);
  716. Q_D(QGLPainter);
  717. QGLPAINTER_CHECK_PRIVATE();
  718. QMatrix4x4 lookAt = camera->modelViewMatrix(d->eye);
  719. d->modelViewMatrix = lookAt;
  720. d->projectionMatrix = camera->projectionMatrix(aspectRatio());
  721. d->inverseEyeMatrix = lookAt.inverted();
  722. }
  723. /*!
  724. Returns true if \a point is outside the current viewing volume.
  725. This is used to perform object culling checks.
  726. */
  727. bool QGLPainter::isCullable(const QVector3D& point) const
  728. {
  729. Q_D(const QGLPainter);
  730. QGLPAINTER_CHECK_PRIVATE();
  731. QVector3D projected = d->modelViewMatrix * point;
  732. projected = d->projectionMatrix * projected;
  733. return !d->viewingCube.contains(projected);
  734. }
  735. static inline uint outcode(const QVector4D &v)
  736. {
  737. // For a discussion of outcodes see pg 388 Dunn & Parberry.
  738. // For why you can't just test if the point is in a bounding box
  739. // consider the case where a view frustum with view-size 1.5 x 1.5
  740. // is tested against a 2x2 box which encloses the near-plane, while
  741. // all the points in the box are outside the frustum.
  742. // TODO: optimise this with assembler - according to D&P this can
  743. // be done in one line of assembler on some platforms
  744. uint code = 0;
  745. if (v.x() < -v.w()) code |= 0x01;
  746. if (v.x() > v.w()) code |= 0x02;
  747. if (v.y() < -v.w()) code |= 0x04;
  748. if (v.y() > v.w()) code |= 0x08;
  749. if (v.z() < -v.w()) code |= 0x10;
  750. if (v.z() > v.w()) code |= 0x20;
  751. return code;
  752. }
  753. /*!
  754. Returns true if \a box is completely outside the current viewing volume.
  755. This is used to perform object culling checks.
  756. */
  757. bool QGLPainter::isCullable(const QBox3D& box) const
  758. {
  759. Q_D(const QGLPainter);
  760. QGLPAINTER_CHECK_PRIVATE();
  761. // This function uses the technique of view frustum culling known as
  762. // clip space testing. Since the normal QVector3D representation
  763. // of the points throws away the w value needed, we convert the box
  764. // into a set of 8 points represented as QVector4D's and then apply
  765. // the test. The test is to transform the points into clip space
  766. // by applying the MV and Proj matrices, then test to see if the 4D
  767. // points are outside the clip space by testing x, y & z against w.
  768. QArray<QVector4D> box4d;
  769. QVector3D n = box.minimum();
  770. QVector3D x = box.maximum();
  771. box4d.append(QVector4D(n.x(), n.y(), x.z(), 1), QVector4D(x.x(), n.y(), x.z(), 1),
  772. QVector4D(x.x(), x.y(), x.z(), 1), QVector4D(n.x(), x.y(), x.z(), 1));
  773. box4d.append(QVector4D(n.x(), n.y(), n.z(), 1), QVector4D(x.x(), n.y(), n.z(), 1),
  774. QVector4D(x.x(), x.y(), n.z(), 1), QVector4D(n.x(), x.y(), n.z(), 1));
  775. QMatrix4x4 mvp = d->projectionMatrix.top() * d->modelViewMatrix.top();
  776. for (int i = 0; i < box4d.size(); ++i)
  777. {
  778. box4d[i] = mvp * box4d.at(i);
  779. }
  780. // if the logical AND of all the outcodes is non-zero then the BB is
  781. // definitely outside the view frustum.
  782. uint out = 0xff;
  783. for (int i = 0; i < box4d.size(); ++i)
  784. {
  785. out = out & outcode(box4d.at(i));
  786. }
  787. return out;
  788. }
  789. /*!
  790. Returns the current render order sequencer.
  791. \sa QGLRenderSequencer
  792. */
  793. QGLRenderSequencer *QGLPainter::renderSequencer()
  794. {
  795. Q_D(QGLPainter);
  796. if (!d->renderSequencer)
  797. d->renderSequencer = new QGLRenderSequencer(this);
  798. return d->renderSequencer;
  799. }
  800. /*!
  801. Returns the aspect ratio of the viewport for adjusting projection
  802. transformations.
  803. */
  804. qreal QGLPainter::aspectRatio() const
  805. {
  806. return currentSurface()->aspectRatio();
  807. }
  808. /*!
  809. Returns the current effect that is in use, which is userEffect()
  810. if it is not null, or the effect object associated with
  811. standardEffect() otherwise.
  812. If isPicking() is true, then this will return the effect object
  813. that is being used to generate pick colors.
  814. \sa userEffect(), standardEffect(), isPicking()
  815. */
  816. QGLAbstractEffect *QGLPainter::effect() const
  817. {
  818. Q_D(QGLPainter);
  819. QGLPAINTER_CHECK_PRIVATE();
  820. d->ensureEffect(const_cast<QGLPainter *>(this));
  821. return d->effect;
  822. }
  823. /*!
  824. Returns the user-defined effect that is being used for drawing
  825. operations, or null if standardEffect() is in use.
  826. \sa setUserEffect(), standardEffect(), effect()
  827. */
  828. QGLAbstractEffect *QGLPainter::userEffect() const
  829. {
  830. Q_D(QGLPainter);
  831. QGLPAINTER_CHECK_PRIVATE();
  832. return d->userEffect;
  833. }
  834. /*!
  835. Sets a user-defined \a effect to use for drawing operations
  836. in the current GL context. If \a effect is null, this will
  837. disable user-defined effects and return to using standardEffect().
  838. \sa effect(), draw(), setStandardEffect()
  839. */
  840. void QGLPainter::setUserEffect(QGLAbstractEffect *effect)
  841. {
  842. Q_D(QGLPainter);
  843. QGLPAINTER_CHECK_PRIVATE();
  844. if (d->userEffect == effect)
  845. return;
  846. if (d->effect)
  847. d->effect->setActive(this, false);
  848. d->userEffect = effect;
  849. if (effect && (!d->pick || !d->pick->isPicking)) {
  850. d->effect = effect;
  851. d->effect->setActive(this, true);
  852. d->updates = UpdateAll;
  853. } else {
  854. // Revert to the effect associated with standardEffect().
  855. d->effect = 0;
  856. d->ensureEffect(this);
  857. }
  858. }
  859. /*!
  860. Returns the standard effect to use for rendering fragments in
  861. the current GL context when userEffect() is null.
  862. \sa setStandardEffect(), userEffect()
  863. */
  864. QGL::StandardEffect QGLPainter::standardEffect() const
  865. {
  866. Q_D(QGLPainter);
  867. QGLPAINTER_CHECK_PRIVATE();
  868. return d->standardEffect;
  869. }
  870. /*!
  871. Sets a standard \a effect to use for rendering fragments
  872. in the current GL context. This will also set userEffect()
  873. to null. If \a effect is an invalid value, then the behavior
  874. of QGL::FlatColor will be used instead.
  875. \sa standardEffect(), setUserEffect()
  876. */
  877. void QGLPainter::setStandardEffect(QGL::StandardEffect effect)
  878. {
  879. Q_D(QGLPainter);
  880. QGLPAINTER_CHECK_PRIVATE();
  881. if (d->standardEffect == effect && d->effect && d->userEffect == 0)
  882. return;
  883. if (d->effect)
  884. d->effect->setActive(this, false);
  885. d->standardEffect = effect;
  886. d->userEffect = 0;
  887. d->effect = 0;
  888. d->ensureEffect(this);
  889. }
  890. /*!
  891. Disables the current effect and sets userEffect() to null.
  892. Unlike setUserEffect() this not activate the standardEffect()
  893. until the next time effect() is called.
  894. This function can be used to disable all effect-based drawing
  895. operations prior to performing raw GL calls. The next time
  896. effect() is called on this QGLPainter, the standardEffect()
  897. will be reactivated. An effect can also be reactivated by
  898. calling setUserEffect() or setStandardEffect().
  899. \sa userEffect(), standardEffect()
  900. */
  901. void QGLPainter::disableEffect()
  902. {
  903. Q_D(QGLPainter);
  904. QGLPAINTER_CHECK_PRIVATE();
  905. if (d->effect)
  906. d->effect->setActive(this, false);
  907. d->userEffect = 0;
  908. d->effect = 0;
  909. }
  910. /*!
  911. Returns the cached shader program associated with \a name; or null
  912. if \a name is not currently associated with a shader program.
  913. \sa setCachedProgram()
  914. */
  915. QOpenGLShaderProgram *QGLPainter::cachedProgram(const QString& name) const
  916. {
  917. Q_D(const QGLPainter);
  918. QGLPAINTER_CHECK_PRIVATE();
  919. return d->cachedPrograms.value(name, 0);
  920. }
  921. /*!
  922. Sets the cached shader \a program associated with \a name.
  923. Effect objects can use this function to store pre-compiled
  924. and pre-linked shader programs in the painter for future
  925. use by the same effect. The \a program will be destroyed
  926. when context() is destroyed.
  927. If \a program is null, then the program associated with \a name
  928. will be destroyed. If \a name is already present as a cached
  929. program, then it will be replaced with \a program.
  930. Names that start with "\c{qt.}" are reserved for use by Qt's
  931. internal effects.
  932. \sa cachedProgram()
  933. */
  934. void QGLPainter::setCachedProgram
  935. (const QString& name, QOpenGLShaderProgram *program)
  936. {
  937. Q_D(QGLPainter);
  938. QGLPAINTER_CHECK_PRIVATE();
  939. QOpenGLShaderProgram *current = d->cachedPrograms.value(name, 0);
  940. if (current != program) {
  941. if (program)
  942. d->cachedPrograms[name] = program;
  943. else
  944. d->cachedPrograms.remove(name);
  945. delete current;
  946. }
  947. }
  948. void QGLPainterPrivate::createEffect(QGLPainter *painter)
  949. {
  950. if (userEffect) {
  951. if (!pick || !pick->isPicking) {
  952. effect = userEffect;
  953. effect->setActive(painter, true);
  954. updates = QGLPainter::UpdateAll;
  955. return;
  956. }
  957. if (userEffect->supportsPicking()) {
  958. effect = userEffect;
  959. effect->setActive(painter, true);
  960. updates = QGLPainter::UpdateAll;
  961. return;
  962. }
  963. effect = pick->defaultPickEffect;
  964. effect->setActive(painter, true);
  965. updates = QGLPainter::UpdateAll;
  966. return;
  967. }
  968. if (uint(standardEffect) >= QGL_MAX_STD_EFFECTS)
  969. effect = stdeffects[int(QGL::FlatColor)];
  970. else
  971. effect = stdeffects[int(standardEffect)];
  972. if (!effect) {
  973. switch (standardEffect) {
  974. case QGL::FlatColor: default:
  975. effect = new QGLFlatColorEffect();
  976. break;
  977. case QGL::FlatPerVertexColor:
  978. effect = new QGLPerVertexColorEffect();
  979. break;
  980. case QGL::FlatReplaceTexture2D:
  981. effect = new QGLFlatTextureEffect();
  982. break;
  983. case QGL::FlatDecalTexture2D:
  984. effect = new QGLFlatDecalTextureEffect();
  985. break;
  986. case QGL::LitMaterial:
  987. effect = new QGLLitMaterialEffect();
  988. break;
  989. case QGL::LitDecalTexture2D:
  990. effect = new QGLLitDecalTextureEffect();
  991. break;
  992. case QGL::LitModulateTexture2D:
  993. effect = new QGLLitModulateTextureEffect();
  994. break;
  995. }
  996. if (uint(standardEffect) >= QGL_MAX_STD_EFFECTS)
  997. stdeffects[int(QGL::FlatColor)] = effect;
  998. else
  999. stdeffects[int(standardEffect)] = effect;
  1000. }
  1001. if (!pick || !pick->isPicking || effect->supportsPicking()) {
  1002. effect->setActive(painter, true);
  1003. } else {
  1004. effect = pick->defaultPickEffect;
  1005. effect->setActive(painter, true);
  1006. }
  1007. updates = QGLPainter::UpdateAll;
  1008. }
  1009. /*!
  1010. Returns the last color that was set with setColor(). The default
  1011. value is (1, 1, 1, 1).
  1012. \sa setColor()
  1013. */
  1014. QColor QGLPainter::color() const
  1015. {
  1016. Q_D(QGLPainter);
  1017. QGLPAINTER_CHECK_PRIVATE();
  1018. return d->color;
  1019. }
  1020. /*!
  1021. Sets the default fragment \a color for effects associated
  1022. with this painter. This function does not apply the color
  1023. to the effect until update() is called.
  1024. \sa color(), update()
  1025. */
  1026. void QGLPainter::setColor(const QColor& color)
  1027. {
  1028. Q_D(QGLPainter);
  1029. QGLPAINTER_CHECK_PRIVATE();
  1030. d->color = color;
  1031. d->updates |= UpdateColor;
  1032. }
  1033. static void qt_gl_setVertexAttribute(QGL::VertexAttribute attribute, const QGLAttributeValue& value)
  1034. {
  1035. #if !defined(QT_OPENGL_ES_2)
  1036. switch (attribute) {
  1037. case QGL::Position:
  1038. glVertexPointer(value.tupleSize(), value.type(),
  1039. value.stride(), value.data());
  1040. break;
  1041. case QGL::Normal:
  1042. if (value.tupleSize() == 3)
  1043. glNormalPointer(value.type(), value.stride(), value.data());
  1044. break;
  1045. case QGL::Color:
  1046. glColorPointer(value.tupleSize(), value.type(),
  1047. value.stride(), value.data());
  1048. break;
  1049. #ifdef GL_TEXTURE_COORD_ARRAY
  1050. case QGL::TextureCoord0:
  1051. case QGL::TextureCoord1:
  1052. case QGL::TextureCoord2:
  1053. {
  1054. int unit = (int)(attribute - QGL::TextureCoord0);
  1055. qt_gl_ClientActiveTexture(GL_TEXTURE0 + unit);
  1056. glTexCoordPointer(value.tupleSize(), value.type(),
  1057. value.stride(), value.data());
  1058. if (unit != 0) // Stay on unit 0 between requests.
  1059. qt_gl_ClientActiveTexture(GL_TEXTURE0);
  1060. }
  1061. break;
  1062. #endif
  1063. default: break;
  1064. }
  1065. #else
  1066. Q_UNUSED(attribute);
  1067. Q_UNUSED(value);
  1068. #endif
  1069. }
  1070. /*!
  1071. Returns the set of vertex attributes that have been set on the
  1072. painter state by setVertexAttribute() and setVertexBundle()
  1073. since the last call to clearAttributes().
  1074. The most common use for this function is to determine if specific
  1075. attributes have been supplied on the painter so as to adjust the
  1076. current drawing effect accordingly. The following example will
  1077. use a lit texture effect if texture co-ordinates were provided
  1078. in the vertex bundle, or a simple lit material effect if
  1079. texture co-ordinates were not provided:
  1080. \code
  1081. painter.clearAttributes();
  1082. painter.setVertexBundle(bundle);
  1083. if (painter.attributes().contains(QGL::TextureCoord0))
  1084. painter.setStandardEffect(QGL::LitModulateTexture2D);
  1085. else
  1086. painter.setStandardEffect(QGL::LitMaterial);
  1087. \endcode
  1088. It is important to clear the attributes before setting the vertex
  1089. bundle, so that attributes from a previous bundle will not leak
  1090. through. Multiple vertex bundles may be supplied if they contain
  1091. different parts of the same logical piece of geometry.
  1092. \sa clearAttributes(), setVertexBundle()
  1093. */
  1094. QGLAttributeSet QGLPainter::attributes() const
  1095. {
  1096. Q_D(const QGLPainter);
  1097. QGLPAINTER_CHECK_PRIVATE();
  1098. return d->attributeSet;
  1099. }
  1100. /*!
  1101. Clears the set of vertex attributes that have been set on the
  1102. painter state by setVertexAttribute() and setVertexBundle().
  1103. See the documentation for attributes() for more information.
  1104. \sa attributes()
  1105. */
  1106. void QGLPainter::clearAttributes()
  1107. {
  1108. Q_D(QGLPainter);
  1109. QGLPAINTER_CHECK_PRIVATE();
  1110. d->attributeSet.clear();
  1111. }
  1112. /*!
  1113. Sets a vertex \a attribute on the current GL context to \a value.
  1114. The vertex attribute is bound to the GL state on the index
  1115. corresponding to \a attribute. For example, QGL::Position
  1116. will be bound to index 0, QGL::TextureCoord0 will be bound
  1117. to index 3, etc.
  1118. Vertex attributes are independent of the effect() and can be
  1119. bound once and then used with multiple effects.
  1120. If this is the first attribute in a new piece of geometry,
  1121. it is recommended that clearAttributes() be called before this
  1122. function. This will inform QGLPainter that a new piece of geometry
  1123. is being provided and that the previous geometry is now invalid.
  1124. See the documentation for attributes() for more information.
  1125. \sa setVertexBundle(), draw(), clearAttributes(), attributes()
  1126. */
  1127. void QGLPainter::setVertexAttribute
  1128. (QGL::VertexAttribute attribute, const QGLAttributeValue& value)
  1129. {
  1130. Q_D(QGLPainter);
  1131. QGLPAINTER_CHECK_PRIVATE();
  1132. d->ensureEffect(this);
  1133. if (d->boundVertexBuffer) {
  1134. QOpenGLBuffer::release(QOpenGLBuffer::VertexBuffer);
  1135. d->boundVertexBuffer = 0;
  1136. }
  1137. if (d->isFixedFunction) {
  1138. qt_gl_setVertexAttribute(attribute, value);
  1139. } else {
  1140. glVertexAttribPointer(GLuint(attribute), value.tupleSize(),
  1141. value.type(), GL_TRUE,
  1142. value.stride(), value.data());
  1143. }
  1144. d->attributeSet.insert(attribute);
  1145. }
  1146. /*!
  1147. Sets the vertex attributes on the current GL context that are
  1148. stored in \a buffer.
  1149. The vertex attributes are bound to the GL state on the indexes
  1150. that are specified within \a buffer; QGL::Position will be
  1151. bound to index 0, QGL::TextureCoord0 will be bound to index 3, etc.
  1152. Vertex attributes are independent of the effect() and can be
  1153. bound once and then used with multiple effects.
  1154. It is recommended that clearAttributes() be called before this
  1155. function to inform QGLPainter that a new piece of geometry is
  1156. being provided and that the previous geometry is now invalid.
  1157. See the documentation for attributes() for more information.
  1158. \sa setVertexAttribute(), draw(), clearAttributes(), attributes()
  1159. */
  1160. void QGLPainter::setVertexBundle(const QGLVertexBundle& buffer)
  1161. {
  1162. Q_D(QGLPainter);
  1163. QGLPAINTER_CHECK_PRIVATE();
  1164. d->ensureEffect(this);
  1165. QGLVertexBundlePrivate *bd = const_cast<QGLVertexBundlePrivate *>(buffer.d_func());
  1166. if (bd->buffer.isCreated()) {
  1167. GLuint id = bd->buffer.bufferId();
  1168. if (id != d->boundVertexBuffer) {
  1169. bd->buffer.bind();
  1170. d->boundVertexBuffer = id;
  1171. }
  1172. } else if (d->boundVertexBuffer) {
  1173. QOpenGLBuffer::release(QOpenGLBuffer::VertexBuffer);
  1174. d->boundVertexBuffer = 0;
  1175. }
  1176. for (int index = 0; index < bd->attributes.size(); ++index) {
  1177. QGLVertexBundleAttribute *attr = bd->attributes[index];
  1178. if (d->isFixedFunction) {
  1179. qt_gl_setVertexAttribute(attr->attribute, attr->value);
  1180. } else {
  1181. glVertexAttribPointer(GLuint(attr->attribute),
  1182. attr->value.tupleSize(),
  1183. attr->value.type(), GL_TRUE,
  1184. attr->value.stride(), attr->value.data());
  1185. }
  1186. }
  1187. d->attributeSet.unite(buffer.attributes());
  1188. }
  1189. /*!
  1190. Updates the projection matrix, modelview matrix, and lighting
  1191. conditions in the currently active effect() object by calling
  1192. QGLAbstractEffect::update(). Also updates \c{glViewport()}
  1193. to cover the currentSurface() if necessary.
  1194. Normally this function is called automatically by draw().
  1195. However, if the user wishes to use raw GL functions to draw fragments,
  1196. it will be necessary to explicitly call this function to ensure that
  1197. the matrix state and lighting conditions have been set on the
  1198. active effect().
  1199. Note that this function informs the effect that an update is needed.
  1200. It does not change the GL state itself, except for \c{glViewport()}.
  1201. In particular, the modelview and projection matrices in the
  1202. fixed-function pipeline are not changed unless the effect or
  1203. application calls updateFixedFunction().
  1204. \sa setUserEffect(), projectionMatrix(), modelViewMatrix()
  1205. \sa draw(), updateFixedFunction()
  1206. */
  1207. void QGLPainter::update()
  1208. {
  1209. Q_D(QGLPainter);
  1210. QGLPAINTER_CHECK_PRIVATE();
  1211. d->ensureEffect(this);
  1212. QGLPainter::Updates updates = d->updates;
  1213. d->updates = 0;
  1214. if (d->modelViewMatrix.isDirty()) {
  1215. updates |= UpdateModelViewMatrix;
  1216. d->modelViewMatrix.setDirty(false);
  1217. }
  1218. if (d->projectionMatrix.isDirty()) {
  1219. updates |= UpdateProjectionMatrix;
  1220. d->projectionMatrix.setDirty(false);
  1221. }
  1222. if ((updates & UpdateViewport) != 0) {
  1223. QRect viewport = currentSurface()->viewportGL();
  1224. glViewport(0, 0, viewport.width(), viewport.height());
  1225. }
  1226. if (updates != 0)
  1227. d->effect->update(this, updates);
  1228. }
  1229. #if !defined(QT_OPENGL_ES_2)
  1230. static void setLight(int light, const QGLLightParameters *parameters,
  1231. const QMatrix4x4& transform)
  1232. {
  1233. GLfloat params[4];
  1234. QColor color = parameters->ambientColor();
  1235. params[0] = color.redF();
  1236. params[1] = color.greenF();
  1237. params[2] = color.blueF();
  1238. params[3] = color.alphaF();
  1239. glLightfv(light, GL_AMBIENT, params);
  1240. color = parameters->diffuseColor();
  1241. params[0] = color.redF();
  1242. params[1] = color.greenF();
  1243. params[2] = color.blueF();
  1244. params[3] = color.alphaF();
  1245. glLightfv(light, GL_DIFFUSE, params);
  1246. color = parameters->specularColor();
  1247. params[0] = color.redF();
  1248. params[1] = color.greenF();
  1249. params[2] = color.blueF();
  1250. params[3] = color.alphaF();
  1251. glLightfv(light, GL_SPECULAR, params);
  1252. QVector4D vector = parameters->eyePosition(transform);
  1253. params[0] = vector.x();
  1254. params[1] = vector.y();
  1255. params[2] = vector.z();
  1256. params[3] = vector.w();
  1257. glLightfv(light, GL_POSITION, params);
  1258. QVector3D spotDirection = parameters->eyeSpotDirection(transform);
  1259. params[0] = spotDirection.x();
  1260. params[1] = spotDirection.y();
  1261. params[2] = spotDirection.z();
  1262. glLightfv(light, GL_SPOT_DIRECTION, params);
  1263. params[0] = parameters->spotExponent();
  1264. glLightfv(light, GL_SPOT_EXPONENT, params);
  1265. params[0] = parameters->spotAngle();
  1266. glLightfv(light, GL_SPOT_CUTOFF, params);
  1267. params[0] = parameters->constantAttenuation();
  1268. glLightfv(light, GL_CONSTANT_ATTENUATION, params);
  1269. params[0] = parameters->linearAttenuation();
  1270. glLightfv(light, GL_LINEAR_ATTENUATION, params);
  1271. params[0] = parameters->quadraticAttenuation();
  1272. glLightfv(light, GL_QUADRATIC_ATTENUATION, params);
  1273. }
  1274. static void setMaterial(int face, const QGLMaterial *parameters)
  1275. {
  1276. GLfloat params[17];
  1277. QColor mcolor = parameters->ambientColor();
  1278. params[0] = mcolor.redF();
  1279. params[1] = mcolor.greenF();
  1280. params[2] = mcolor.blueF();
  1281. params[3] = mcolor.alphaF();
  1282. mcolor = parameters->diffuseColor();
  1283. params[4] = mcolor.redF();
  1284. params[5] = mcolor.greenF();
  1285. params[6] = mcolor.blueF();
  1286. params[7] = mcolor.alphaF();
  1287. mcolor = parameters->specularColor();
  1288. params[8] = mcolor.redF();
  1289. params[9] = mcolor.greenF();
  1290. params[10] = mcolor.blueF();
  1291. params[11] = mcolor.alphaF();
  1292. mcolor = parameters->emittedLight();
  1293. params[12] = mcolor.redF();
  1294. params[13] = mcolor.greenF();
  1295. params[14] = mcolor.blueF();
  1296. params[15] = mcolor.alphaF();
  1297. params[16] = parameters->shininess();
  1298. glMaterialfv(face, GL_AMBIENT, params);
  1299. glMaterialfv(face, GL_DIFFUSE, params + 4);
  1300. glMaterialfv(face, GL_SPECULAR, params + 8);
  1301. glMaterialfv(face, GL_EMISSION, params + 12);
  1302. glMaterialfv(face, GL_SHININESS, params + 16);
  1303. }
  1304. #endif // !QT_OPENGL_ES_2
  1305. /*!
  1306. Updates the fixed-function pipeline with the current painting
  1307. state according to the flags in \a updates.
  1308. This function is intended for use by effects in their
  1309. QGLAbstractEffect::update() override if they are using the
  1310. fixed-function pipeline. It can also be used by user
  1311. applications if they need the QGLPainter state to be
  1312. set in the fixed-function pipeline.
  1313. If the OpenGL implementation does not have a fixed-function
  1314. pipeline, e.g. OpenGL/ES 2.0, this function does nothing.
  1315. \sa update()
  1316. */
  1317. void QGLPainter::updateFixedFunction(QGLPainter::Updates updates)
  1318. {
  1319. #if defined(QT_OPENGL_ES_2)
  1320. Q_UNUSED(updates);
  1321. #else
  1322. Q_D(QGLPainter);
  1323. QGLPAINTER_CHECK_PRIVATE();
  1324. if ((updates & QGLPainter::UpdateColor) != 0) {
  1325. QColor color;
  1326. if (isPicking())
  1327. color = pickColor();
  1328. else
  1329. color = this->color();
  1330. glColor4f(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  1331. }
  1332. if ((updates & QGLPainter::UpdateModelViewMatrix) != 0) {
  1333. const QMatrix4x4 &matrix = d->modelViewMatrix.top();
  1334. glMatrixMode(GL_MODELVIEW);
  1335. if (sizeof(qreal) == sizeof(GLfloat)) {
  1336. glLoadMatrixf(reinterpret_cast<const GLfloat *>
  1337. (matrix.constData()));
  1338. } else {
  1339. GLfloat mat[16];
  1340. const qreal *m = matrix.constData();
  1341. for (int index = 0; index < 16; ++index)
  1342. mat[index] = m[index];
  1343. glLoadMatrixf(mat);
  1344. }
  1345. }
  1346. if ((updates & QGLPainter::UpdateProjectionMatrix) != 0) {
  1347. const QMatrix4x4 &matrix = d->projectionMatrix.top();
  1348. glMatrixMode(GL_PROJECTION);
  1349. if (sizeof(qreal) == sizeof(GLfloat)) {
  1350. glLoadMatrixf(reinterpret_cast<const GLfloat *>
  1351. (matrix.constData()));
  1352. } else {
  1353. GLfloat mat[16];
  1354. const qreal *m = matrix.constData();
  1355. for (int index = 0; index < 16; ++index)
  1356. mat[index] = m[index];
  1357. glLoadMatrixf(mat);
  1358. }
  1359. }
  1360. if ((updates & QGLPainter::UpdateLights) != 0) {
  1361. // Save the current modelview matrix and load the identity.
  1362. // We need to apply the light in the modelview transformation
  1363. // that was active when the light was specified.
  1364. glMatrixMode(GL_MODELVIEW);
  1365. glPushMatrix();
  1366. glLoadIdentity();
  1367. // Enable the main light.
  1368. const QGLLightParameters *params = mainLight();
  1369. setLight(GL_LIGHT0, params, mainLightTransform());
  1370. // Restore the previous modelview transformation.
  1371. glPopMatrix();
  1372. // Set up the light model parameters if at least one light is enabled.
  1373. const QGLLightModel *lightModel = this->lightModel();
  1374. GLfloat values[4];
  1375. #ifdef GL_LIGHT_MODEL_TWO_SIDE
  1376. if (lightModel->model() == QGLLightModel::TwoSided)
  1377. values[0] = 1.0f;
  1378. else
  1379. values[0] = 0.0f;
  1380. glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, values);
  1381. #endif
  1382. #ifdef GL_LIGHT_MODEL_COLOR_CONTROL
  1383. if (lightModel->colorControl() == QGLLightModel::SeparateSpecularColor)
  1384. values[0] = GL_SEPARATE_SPECULAR_COLOR;
  1385. else
  1386. values[0] = GL_SINGLE_COLOR;
  1387. glLightModelfv(GL_LIGHT_MODEL_COLOR_CONTROL, values);
  1388. #endif
  1389. #ifdef GL_LIGHT_MODEL_LOCAL_VIEWER
  1390. if (lightModel->viewerPosition() == QGLLightModel::LocalViewer)
  1391. values[0] = 1.0f;
  1392. else
  1393. values[0] = 0.0f;
  1394. glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, values);
  1395. #endif
  1396. #ifdef GL_LIGHT_MODEL_AMBIENT
  1397. QColor color = lightModel->ambientSceneColor();
  1398. values[0] = color.redF();
  1399. values[1] = color.blueF();
  1400. values[2] = color.greenF();
  1401. values[3] = color.alphaF();
  1402. glLightModelfv(GL_LIGHT_MODEL_AMBIENT, values);
  1403. #endif
  1404. }
  1405. if ((updates & QGLPainter::UpdateMaterials) != 0) {
  1406. const QGLMaterial *frontMaterial = faceMaterial(QGL::FrontFaces);
  1407. const QGLMaterial *backMaterial = faceMaterial(QGL::BackFaces);
  1408. if (frontMaterial == backMaterial) {
  1409. setMaterial(GL_FRONT_AND_BACK, frontMaterial);
  1410. } else {
  1411. setMaterial(GL_FRONT, frontMaterial);
  1412. setMaterial(GL_BACK, backMaterial);
  1413. }
  1414. }
  1415. #endif
  1416. }
  1417. /*!
  1418. Draws primitives using \a count vertices from the arrays specified
  1419. by setVertexAttribute(). The type of primitive to draw is specified
  1420. by \a mode.
  1421. This operation will consume \a count values from the
  1422. enabled arrays, starting at \a index.
  1423. \sa update()
  1424. */
  1425. void QGLPainter::draw(QGL::DrawingMode mode, int count, int index)
  1426. {
  1427. update();
  1428. glDrawArrays((GLenum)mode, index, count);
  1429. }
  1430. /*!
  1431. \overload
  1432. Draws primitives using vertices from the arrays specified by
  1433. setVertexAttribute(). The type of primitive to draw is
  1434. specified by \a mode.
  1435. This operation will consume \a count elements of \a indices,
  1436. which are used to index into the enabled arrays.
  1437. \sa update()
  1438. */
  1439. void QGLPainter::draw(QGL::DrawingMode mode, const ushort *indices, int count)
  1440. {
  1441. Q_D(QGLPainter);
  1442. QGLPAINTER_CHECK_PRIVATE();
  1443. update();
  1444. if (d->boundIndexBuffer) {
  1445. QOpenGLBuffer::release(QOpenGLBuffer::IndexBuffer);
  1446. d->boundIndexBuffer = 0;
  1447. }
  1448. glDrawElements(GLenum(mode), count, GL_UNSIGNED_SHORT, indices);
  1449. }
  1450. /*!
  1451. Pushes \a surface onto the surface stack and makes it the current
  1452. drawing surface for context(). If \a surface is null, then the
  1453. current drawing surface will be set to the main surface (e.g. the window).
  1454. Note: the \a surface object must remain valid until popped from
  1455. the stack or end() is called. All surfaces are popped from
  1456. the stack by end().
  1457. The UpdateViewport flag will be set to indicate that the
  1458. \c{glViewport()} should be adjusted to the extents of \a surface
  1459. when update() is next called.
  1460. \sa popSurface(), currentSurface(), setSurface()
  1461. \sa QGLAbstractSurface::activate()
  1462. */
  1463. void QGLPainter::pushSurface(QGLAbstractSurface *surface)
  1464. {
  1465. Q_D(QGLPainter);
  1466. QGLPAINTER_CHECK_PRIVATE();
  1467. Q_ASSERT(surface);
  1468. if (!surface) {
  1469. // Find the most recent main surface for this painter.
  1470. int size = d->surfaceStack.size();
  1471. while (size > 0 && !d->surfaceStack[size - 1].mainSurface)
  1472. --size;
  1473. if (!size)
  1474. return; // Shouldn't happen, but be safe anyway.
  1475. surface = d->surfaceStack[size - 1].surface;
  1476. }
  1477. Q_ASSERT(!d->surfaceStack.isEmpty()); // Should have a main surface.
  1478. QGLAbstractSurface *current = d->surfaceStack.top().surface;
  1479. QGLPainterSurfaceInfo psurf;
  1480. psurf.surface = surface;
  1481. psurf.destroySurface = false;
  1482. psurf.mainSurface = false;
  1483. d->surfaceStack.append(psurf);
  1484. current->switchTo(surface);
  1485. d->updates |= UpdateViewport;
  1486. }
  1487. /*!
  1488. Pops the top-most drawing surface from the surface stack
  1489. and returns it. The next object on the stack will be made
  1490. the current drawing surface for context(). Returns null if the
  1491. surface stack is already at the main surface (e.g. the window).
  1492. The UpdateViewport flag will be set to indicate that the
  1493. \c{glViewport()} should be adjusted to the new surface extents
  1494. when update() is next called.
  1495. \sa pushSurface(), currentSurface(), setSurface()
  1496. */
  1497. QGLAbstractSurface *QGLPainter::popSurface()
  1498. {
  1499. Q_D(QGLPainter);
  1500. QGLPAINTER_CHECK_PRIVATE();
  1501. Q_ASSERT(!d->surfaceStack.isEmpty()); // Should have a main surface.
  1502. QGLPainterSurfaceInfo &surf = d->surfaceStack.top();
  1503. if (surf.mainSurface)
  1504. return 0;
  1505. QGLAbstractSurface *surface = surf.surface;
  1506. d->surfaceStack.pop();
  1507. Q_ASSERT(!d->surfaceStack.isEmpty()); // Should have a main surface.
  1508. QGLAbstractSurface *nextSurface = d->surfaceStack.top().surface;
  1509. surface->switchTo(nextSurface);
  1510. d->updates |= UpdateViewport;
  1511. return surface;
  1512. }
  1513. /*!
  1514. Sets the top-most drawing surface on the surface stack to \a surface
  1515. and activate it.
  1516. Note: if the top-most drawing surface is the main surface specified
  1517. during begin(), then this function will perform a pushSurface()
  1518. instead. Typically this function is used to replace the last
  1519. surface that was pushed onto the stack and avoid doing popSurface()
  1520. followed by pushSurface(). The main surface cannot be replaced
  1521. in this manner.
  1522. The UpdateViewport flag will be set to indicate that the
  1523. \c{glViewport()} should be adjusted to the extents of \a surface
  1524. when update() is next called.
  1525. \sa pushSurface(), popSurface(), currentSurface()
  1526. */
  1527. void QGLPainter::setSurface(QGLAbstractSurface *surface)
  1528. {
  1529. Q_D(QGLPainter);
  1530. QGLPAINTER_CHECK_PRIVATE();
  1531. Q_ASSERT(surface);
  1532. Q_ASSERT(!d->surfaceStack.isEmpty()); // Should have a main surface.
  1533. QGLPainterSurfaceInfo &surf = d->surfaceStack.top();
  1534. if (surf.mainSurface) {
  1535. pushSurface(surface);
  1536. return;
  1537. }
  1538. QGLAbstractSurface *oldSurface = surf.surface;
  1539. surf.surface = surface;
  1540. oldSurface->switchTo(surface);
  1541. d->updates |= UpdateViewport;
  1542. }
  1543. /*!
  1544. Returns the current drawing surface.
  1545. \sa pushSurface(), popSurface(), setSurface()
  1546. */
  1547. QGLAbstractSurface *QGLPainter::currentSurface() const
  1548. {
  1549. Q_D(const QGLPainter);
  1550. QGLPAINTER_CHECK_PRIVATE();
  1551. Q_ASSERT(!d->surfaceStack.isEmpty()); // Should have a main surface.
  1552. return d->surfaceStack.top().surface;
  1553. }
  1554. /*!
  1555. Returns the current lighting model.
  1556. \sa setLightModel()
  1557. */
  1558. const QGLLightModel *QGLPainter::lightModel() const
  1559. {
  1560. Q_D(QGLPainter);
  1561. QGLPAINTER_CHECK_PRIVATE();
  1562. if (!d->lightModel) {
  1563. if (!d->defaultLightModel)
  1564. d->defaultLightModel = new QGLLightModel();
  1565. d->lightModel = d->defaultLightModel;
  1566. }
  1567. return d->lightModel;
  1568. }
  1569. /*!
  1570. Sets the current lighting model to \a value. If \a value is
  1571. null, then the default lighting model parameters will be used.
  1572. The light settings in the GL server will not be changed until
  1573. update() is called.
  1574. \sa lightModel()
  1575. */
  1576. void QGLPainter::setLightModel(const QGLLightModel *value)
  1577. {
  1578. Q_D(QGLPainter);
  1579. QGLPAINTER_CHECK_PRIVATE();
  1580. d->lightModel = value;
  1581. d->updates |= QGLPainter::UpdateLights;
  1582. }
  1583. /*!
  1584. Returns the parameters for the main light in the scene.
  1585. The light parameters are specified in world co-ordinates at
  1586. the point when setMainLight() was called. The mainLightTransform()
  1587. must be applied to obtain eye co-ordinates.
  1588. This function is a convenience that returns the light with
  1589. identifier 0. If light 0 is not currently enabled, then a
  1590. default light is added to the painter with an identity
  1591. transform and then returned as the main light.
  1592. \sa setMainLight(), mainLightTransform(), addLight()
  1593. */
  1594. const QGLLightParameters *QGLPainter::mainLight() const
  1595. {
  1596. Q_D(QGLPainter);
  1597. QGLPAINTER_CHECK_PRIVATE();
  1598. if (d->lights.isEmpty()) {
  1599. if (!d->defaultLight)
  1600. d->defaultLight = new QGLLightParameters();
  1601. d->lights.append(d->defaultLight);
  1602. d->lightTransforms.append(QMatrix4x4());
  1603. } else if (!d->lights[0]) {
  1604. if (!d->defaultLight)
  1605. d->defaultLight = new QGLLightParameters();
  1606. d->lights[0] = d->defaultLight;
  1607. d->lightTransforms[0] = QMatrix4x4();
  1608. }
  1609. return d->lights[0];
  1610. }
  1611. /*!
  1612. Sets the \a parameters for the main light in the scene.
  1613. The mainLightTransform() is set to the current modelViewMatrix().
  1614. Light parameters are stored in world co-ordinates, not eye co-ordinates.
  1615. The mainLightTransform() specifies the transformation to apply to
  1616. convert the world co-ordinates into eye co-ordinates when the light
  1617. is used.
  1618. Note: the \a parameters may be ignored by effect() if it
  1619. has some other way to determine the lighting conditions.
  1620. The light settings in the GL server will not be changed until
  1621. update() is called.
  1622. This function is a convenience that sets the light with
  1623. identifier 0. If \a parameters is null, then light 0
  1624. will be removed.
  1625. \sa mainLight(), mainLightTransform(), addLight()
  1626. */
  1627. void QGLPainter::setMainLight(const QGLLightParameters *parameters)
  1628. {
  1629. Q_D(QGLPainter);
  1630. QGLPAINTER_CHECK_PRIVATE();
  1631. if (d->lights.isEmpty()) {
  1632. if (parameters) {
  1633. d->lights.append(parameters);
  1634. d->lightTransforms.append(modelViewMatrix());
  1635. d->updates |= QGLPainter::UpdateLights;
  1636. }
  1637. } else if (parameters) {
  1638. d->lights[0] = parameters;
  1639. d->lightTransforms[0] = modelViewMatrix();
  1640. d->updates |= QGLPainter::UpdateLights;
  1641. } else {
  1642. removeLight(0);
  1643. }
  1644. }
  1645. /*!
  1646. Sets the \a parameters for the main light in the scene, and set
  1647. mainLightTransform() to \a transform.
  1648. Light parameters are stored in world co-ordinates, not eye co-ordinates.
  1649. The \a transform specifies the transformation to apply to convert the
  1650. world co-ordinates into eye co-ordinates when the light is used.
  1651. Note: the \a parameters may be ignored by effect() if it
  1652. has some other way to determine the lighting conditions.
  1653. The light settings in the GL server will not be changed until
  1654. update() is called.
  1655. This function is a convenience that sets the light with
  1656. identifier 0. If \a parameters is null, then light 0
  1657. will be removed.
  1658. \sa mainLight(), mainLightTransform()
  1659. */
  1660. void QGLPainter::setMainLight
  1661. (const QGLLightParameters *parameters, const QMatrix4x4& transform)
  1662. {
  1663. Q_D(QGLPainter);
  1664. QGLPAINTER_CHECK_PRIVATE();
  1665. if (d->lights.isEmpty()) {
  1666. if (parameters) {
  1667. d->lights.append(parameters);
  1668. d->lightTransforms.append(transform);
  1669. d->updates |= QGLPainter::UpdateLights;
  1670. }
  1671. } else if (parameters) {
  1672. d->lights[0] = parameters;
  1673. d->lightTransforms[0] = transform;
  1674. d->updates |= QGLPainter::UpdateLights;
  1675. } else {
  1676. removeLight(0);
  1677. }
  1678. }
  1679. /*!
  1680. Returns the modelview transformation matrix for the main light that
  1681. was set at the time setMainLight() was called.
  1682. The light transform may be used by later painting operations to
  1683. convert the light from world co-ordinates into eye co-ordinates.
  1684. The eye transformation is set when the light is specified.
  1685. This function is a convenience that returns the tranform for the
  1686. light with identifier 0. If light 0 is not enabled, then the
  1687. function returns the identity matrix.
  1688. \sa mainLight(), setMainLight(), addLight()
  1689. */
  1690. QMatrix4x4 QGLPainter::mainLightTransform() const
  1691. {
  1692. Q_D(const QGLPainter);
  1693. QGLPAINTER_CHECK_PRIVATE();
  1694. if (!d->lights.isEmpty() && d->lights[0])
  1695. return d->lightTransforms[0];
  1696. else
  1697. return QMatrix4x4();
  1698. }
  1699. /*!
  1700. Adds a light to this painter, with the specified \a parameters.
  1701. The lightTransform() for the light is set to the current
  1702. modelViewMatrix(). Returns an identifier for the light.
  1703. Light parameters are stored in world co-ordinates, not eye co-ordinates.
  1704. The lightTransform() specifies the transformation to apply to
  1705. convert the world co-ordinates into eye co-ordinates when the light
  1706. is used.
  1707. Note: the \a parameters may be ignored by effect() if it
  1708. has some other way to determine the lighting conditions.
  1709. The light settings in the GL server will not be changed until
  1710. update() is called.
  1711. \sa removeLight(), light(), mainLight()
  1712. */
  1713. int QGLPainter::addLight(const QGLLightParameters *parameters)
  1714. {
  1715. return addLight(parameters, modelViewMatrix());
  1716. }
  1717. /*!
  1718. Adds a light to this painter, with the specified \a parameters.
  1719. The lightTransform() for the light is set to \a transform.
  1720. Returns an identifier for the light.
  1721. Light parameters are stored in world co-ordinates, not eye co-ordinates.
  1722. The \a transform specifies the transformation to apply to
  1723. convert the world co-ordinates into eye co-ordinates when the light
  1724. is used.
  1725. Note: the \a parameters may be ignored by effect() if it
  1726. has some other way to determine the lighting conditions.
  1727. The light settings in the GL server will not be changed until
  1728. update() is called.
  1729. \sa removeLight(), light(), mainLight()
  1730. */
  1731. int QGLPainter::addLight(const QGLLightParameters *parameters, const QMatrix4x4 &transform)
  1732. {
  1733. Q_ASSERT(parameters);
  1734. Q_D(QGLPainter);
  1735. QGLPAINTER_CHECK_PRIVATE();
  1736. int lightId = 0;
  1737. while (lightId < d->lights.size() && d->lights[lightId] != 0)
  1738. ++lightId;
  1739. if (lightId < d->lights.size()) {
  1740. d->lights[lightId] = parameters;
  1741. d->lightTransforms[lightId] = transform;
  1742. } else {
  1743. d->lights.append(parameters);
  1744. d->lightTransforms.append(transform);
  1745. }
  1746. d->updates |= QGLPainter::UpdateLights;
  1747. return lightId;
  1748. }
  1749. /*!
  1750. Removes the light with the specified \a lightId.
  1751. \sa addLight(), light()
  1752. */
  1753. void QGLPainter::removeLight(int lightId)
  1754. {
  1755. Q_D(QGLPainter);
  1756. QGLPAINTER_CHECK_PRIVATE();
  1757. if (lightId >= 0 && lightId < d->lights.size()) {
  1758. d->lights[lightId] = 0;
  1759. if (lightId >= (d->lights.size() - 1)) {
  1760. do {
  1761. d->lights.resize(lightId);
  1762. d->lightTransforms.resize(lightId);
  1763. --lightId;
  1764. } while (lightId >= 0 && d->lights[lightId] == 0);
  1765. }
  1766. d->updates |= QGLPainter::UpdateLights;
  1767. }
  1768. }
  1769. /*!
  1770. Returns the maximum light identifier currently in use on this painter;
  1771. or -1 if there are no lights.
  1772. It is possible that some light identifiers less than maximumLightId()
  1773. may be invalid because the lights have been removed. Use the following
  1774. code to locate all enabled lights:
  1775. \code
  1776. int maxLightId = painter.maximumLightId();
  1777. for (int lightId = 0; index <= maxLightId; ++index) {
  1778. const QGLLightParameters *params = painter.light(lightId);
  1779. if (params) {
  1780. ...
  1781. }
  1782. }
  1783. \endcode
  1784. \sa addLight(), light()
  1785. */
  1786. int QGLPainter::maximumLightId() const
  1787. {
  1788. Q_D(const QGLPainter);
  1789. QGLPAINTER_CHECK_PRIVATE();
  1790. return d->lights.size() - 1;
  1791. }
  1792. /*!
  1793. Returns the parameters for the light with the identifier \a lightId;
  1794. or null if \a lightId is not valid or has been removed.
  1795. \sa addLight(), removeLight(), lightTransform()
  1796. */
  1797. const QGLLightParameters *QGLPainter::light(int lightId) const
  1798. {
  1799. Q_D(const QGLPainter);
  1800. QGLPAINTER_CHECK_PRIVATE();
  1801. if (lightId >= 0 && lightId < d->lights.size())
  1802. return d->lights[lightId];
  1803. else
  1804. return 0;
  1805. }
  1806. /*!
  1807. Returns the modelview transformation for the light with the identifier
  1808. \a lightId; or the identity matrix if \a lightId is not valid or has
  1809. been removed.
  1810. \sa addLight(), removeLight(), light()
  1811. */
  1812. QMatrix4x4 QGLPainter::lightTransform(int lightId) const
  1813. {
  1814. Q_D(const QGLPainter);
  1815. QGLPAINTER_CHECK_PRIVATE();
  1816. if (lightId >= 0 && lightId < d->lights.size() && d->lights[lightId])
  1817. return d->lightTransforms[lightId];
  1818. else
  1819. return QMatrix4x4();
  1820. }
  1821. /*!
  1822. Returns the material that is used for drawing \a face on polygons.
  1823. If \a face is QGL::FrontFaces or QGL::AllFaces, then the front
  1824. material is returned. If \a face is QGL::BackFaces, then the
  1825. back material is returned.
  1826. \sa setFaceMaterial(), setFaceColor()
  1827. */
  1828. const QGLMaterial *QGLPainter::faceMaterial(QGL::Face face) const
  1829. {
  1830. Q_D(QGLPainter);
  1831. QGLPAINTER_CHECK_PRIVATE();
  1832. if (face == QGL::BackFaces) {
  1833. if (!d->backMaterial) {
  1834. if (!d->defaultMaterial)
  1835. d->defaultMaterial = new QGLMaterial();
  1836. d->backMaterial = d->defaultMaterial;
  1837. }
  1838. return d->backMaterial;
  1839. } else {
  1840. if (!d->frontMaterial) {
  1841. if (!d->defaultMaterial)
  1842. d->defaultMaterial = new QGLMaterial();
  1843. d->frontMaterial = d->defaultMaterial;
  1844. }
  1845. return d->frontMaterial;
  1846. }
  1847. }
  1848. /*!
  1849. Sets the material that is used for drawing \a face on polygons
  1850. to \a value. If \a face is QGL::FrontFaces, then the front
  1851. material is set. If \a face is QGL::BackFaces, then the
  1852. back material is set. If \a face is QGL::AllFaces, then both
  1853. the front and back materials are set.
  1854. If \a value is null, then the \a face material will be set to
  1855. the default material properties.
  1856. The material settings in the GL server will not be changed until
  1857. update() is called.
  1858. \sa faceMaterial(), setFaceColor()
  1859. */
  1860. void QGLPainter::setFaceMaterial
  1861. (QGL::Face face, const QGLMaterial *value)
  1862. {
  1863. Q_D(QGLPainter);
  1864. QGLPAINTER_CHECK_PRIVATE();
  1865. if (face == QGL::FrontFaces) {
  1866. if (d->frontMaterial == value)
  1867. return;
  1868. d->frontMaterial = value;
  1869. } else if (face == QGL::BackFaces) {
  1870. if (d->backMaterial == value)
  1871. return;
  1872. d->backMaterial = value;
  1873. } else {
  1874. if (d->frontMaterial == value && d->backMaterial == value)
  1875. return;
  1876. d->frontMaterial = value;
  1877. d->backMaterial = value;
  1878. }
  1879. d->updates |= QGLPainter::UpdateMaterials;
  1880. }
  1881. static QGLMaterial *createColorMaterial
  1882. (QGLMaterial *prev, const QColor& color)
  1883. {
  1884. QGLMaterial *material;
  1885. if (prev)
  1886. material = prev;
  1887. else
  1888. material = new QGLMaterial();
  1889. material->setColor(color);
  1890. return material;
  1891. }
  1892. /*!
  1893. Sets the material that is used for drawing \a face on polygons
  1894. to \a color. This is a convenience function for setting materials
  1895. to simple colors.
  1896. The RGB components of the ambient color of the material will be set
  1897. to 20% of \a color, and the RGB components of the diffuse color of the
  1898. material will be set to 80% of \a color. The alpha components of
  1899. the ambient and diffuse material colors will both be set to the
  1900. alpha component of \a color.
  1901. If \a face is QGL::FrontFaces, then the front material is set.
  1902. If \a face is QGL::BackFaces, then the back material is set.
  1903. If \a face is QGL::AllFaces, then both the front and back
  1904. materials are set.
  1905. The material settings in the GL server will not be changed until
  1906. update() is called.
  1907. \sa faceMaterial(), setFaceMaterial()
  1908. */
  1909. void QGLPainter::setFaceColor(QGL::Face face, const QColor& color)
  1910. {
  1911. Q_D(QGLPainter);
  1912. QGLPAINTER_CHECK_PRIVATE();
  1913. if (face == QGL::FrontFaces) {
  1914. d->frontColorMaterial =
  1915. createColorMaterial(d->frontColorMaterial, color);
  1916. d->frontMaterial = d->frontColorMaterial;
  1917. } else if (face == QGL::BackFaces) {
  1918. d->backColorMaterial =
  1919. createColorMaterial(d->backColorMaterial, color);
  1920. d->backMaterial = d->backColorMaterial;
  1921. } else {
  1922. d->frontColorMaterial =
  1923. createColorMaterial(d->frontColorMaterial, color);
  1924. d->backColorMaterial =
  1925. createColorMaterial(d->backColorMaterial, color);
  1926. d->frontMaterial = d->frontColorMaterial;
  1927. d->backMaterial = d->backColorMaterial;
  1928. }
  1929. d->updates |= QGLPainter::UpdateMaterials;
  1930. }
  1931. /*!
  1932. Returns true if this painter is in object picking mode;
  1933. false if this painter is in normal rendering mode.
  1934. \sa setPicking(), objectPickId()
  1935. */
  1936. bool QGLPainter::isPicking() const
  1937. {
  1938. Q_D(QGLPainter);
  1939. QGLPAINTER_CHECK_PRIVATE();
  1940. return (d->pick ? d->pick->isPicking : false);
  1941. }
  1942. /*!
  1943. Enables or disables object picking mode according to \a value.
  1944. If \a value is true, then the effect() will be overridden with a
  1945. simple flat color effect that renders objects with pickColor().
  1946. These colors can be read back later with pickObject().
  1947. \sa isPicking(), objectPickId(), pickObject()
  1948. */
  1949. void QGLPainter::setPicking(bool value)
  1950. {
  1951. Q_D(QGLPainter);
  1952. QGLPAINTER_CHECK_PRIVATE();
  1953. if (!d->pick)
  1954. d->pick = new QGLPainterPickPrivate();
  1955. if (d->pick->isPicking != value) {
  1956. // Switch to/from the pick effect.
  1957. d->pick->isPicking = value;
  1958. if (d->effect)
  1959. d->effect->setActive(this, false);
  1960. d->effect = 0;
  1961. d->ensureEffect(this);
  1962. }
  1963. }
  1964. /*!
  1965. Returns the current object pick identifier. The default value
  1966. is -1 which indicates that rendered objects should not have a
  1967. pickColor() associated with them.
  1968. \sa setObjectPickId(), clearPickObjects(), pickObject()
  1969. */
  1970. int QGLPainter::objectPickId() const
  1971. {
  1972. Q_D(QGLPainter);
  1973. QGLPAINTER_CHECK_PRIVATE();
  1974. return (d->pick ? d->pick->objectPickId : -1);
  1975. }
  1976. /*!
  1977. Sets the current object pick identifier to \a value. If \a value
  1978. is -1, then subsequent objects will be rendered without a pickColor().
  1979. If value is not -1, then the pickColor() is changed to a color
  1980. that represents that object pick identifier. If \a value has been
  1981. seen previously, then the same pickColor() as last time will
  1982. be returned.
  1983. The function call will be ignored if isPicking() is false.
  1984. \sa objectPickId(), clearPickObjects(), pickObject()
  1985. */
  1986. void QGLPainter::setObjectPickId(int value)
  1987. {
  1988. Q_D(QGLPainter);
  1989. QGLPAINTER_CHECK_PRIVATE();
  1990. if (!d->pick || !d->pick->isPicking)
  1991. return;
  1992. d->pick->objectPickId = value;
  1993. if (value != -1) {
  1994. QRgb color = d->pick->pickObjectToColor.value(value, 0);
  1995. if (!color) {
  1996. color = qt_qgl_pick_color(d->pick->pickColorIndex++);
  1997. d->pick->pickObjectToColor[value] = color;
  1998. d->pick->pickColorToObject[color] = value;
  1999. }
  2000. d->pick->pickColor = color;
  2001. d->updates |= UpdateColor;
  2002. } else {
  2003. d->pick->pickColor = 0;
  2004. d->updates |= UpdateColor;
  2005. }
  2006. }
  2007. /*!
  2008. Clears the objectPickId() to pickColor() mappings that
  2009. were used previously. This will also set objectPickId()
  2010. to -1 and pickColor() to (0, 0, 0, 1).
  2011. The function call will be ignored if isPicking() is false.
  2012. \sa objectPickId(), pickColor()
  2013. */
  2014. void QGLPainter::clearPickObjects()
  2015. {
  2016. Q_D(QGLPainter);
  2017. QGLPAINTER_CHECK_PRIVATE();
  2018. if (d->pick && d->pick->isPicking) {
  2019. d->pick->pickObjectToColor.clear();
  2020. d->pick->pickColorToObject.clear();
  2021. d->pick->pickColorIndex = 0;
  2022. d->pick->objectPickId = -1;
  2023. d->pick->pickColor = 0;
  2024. d->updates |= UpdateColor;
  2025. }
  2026. }
  2027. /*!
  2028. Returns the current pick color to use to render the object
  2029. associated with objectPickId(). The returned color will
  2030. be (0, 0, 0, 1) if objectPickId() is -1.
  2031. \sa objectPickId(), clearPickObjects()
  2032. */
  2033. QColor QGLPainter::pickColor() const
  2034. {
  2035. Q_D(QGLPainter);
  2036. QGLPAINTER_CHECK_PRIVATE();
  2037. if (d->pick) {
  2038. QColor color;
  2039. color.setRgb(d->pick->pickColor);
  2040. return color;
  2041. } else {
  2042. return Qt::black;
  2043. }
  2044. }
  2045. /*!
  2046. Picks the color at (\a x, \a y) in the color buffer and
  2047. returns the objectPickId() that corresponds to that color.
  2048. Returns -1 if (\a x, \a y) is not positioned over a
  2049. recognized object. The origin (0, 0) is assumed to be
  2050. the bottom-left corner of the drawing surface.
  2051. \sa objectPickId()
  2052. */
  2053. int QGLPainter::pickObject(int x, int y) const
  2054. {
  2055. Q_D(QGLPainter);
  2056. QGLPAINTER_CHECK_PRIVATE();
  2057. if (!d->pick)
  2058. {
  2059. return -1;
  2060. }
  2061. // Fetch the color at the specified pixel.
  2062. unsigned char data[4] = {0, 0, 0, 0};
  2063. glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, data);
  2064. QRgb color = qRgb(data[0], data[1], data[2]);
  2065. // Normalize the color to account for floating-point rounding.
  2066. color = qt_qgl_normalize_pick_color(color); // XXX: detect RGB444 screens.
  2067. // Map the color back to an object identifier.
  2068. return d->pick->pickColorToObject.value(color, -1);
  2069. }
  2070. QT_END_NAMESPACE