Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

Fix Mesh Memory Leak

Anderson Prado9bacac682ca7
diff --git a/toonz/sources/toonzlib/plasticdeformerfx.cpp b/toonz/sources/toonzlib/plasticdeformerfx.cpp
index c46d9e914..0e0309dc2 100644
--- a/toonz/sources/toonzlib/plasticdeformerfx.cpp
+++ b/toonz/sources/toonzlib/plasticdeformerfx.cpp
@@ -10,6 +10,7 @@
#include "toonz/txshlevelcolumn.h"
#include "toonz/dpiscale.h"
#include "toonz/stage.h"
+#include "toonz/tlog.h"
// TnzExt includes
#include "ext/plasticskeleton.h"
@@ -33,6 +34,8 @@
#include <QSurfaceFormat>
#include <QOpenGLContext>
#include <QImage>
+#include <QThread>
+#include <algorithm>
FX_IDENTIFIER_IS_HIDDEN(PlasticDeformerFx, "plasticDeformerFx")
@@ -43,15 +46,14 @@ FX_IDENTIFIER_IS_HIDDEN(PlasticDeformerFx, "plasticDeformerFx")
namespace {
std::string toString(const TAffine &aff) {
- return
- // Observe that toString distinguishes + and - 0. That is a problem
- // when comparing aliases - so near 0 values are explicitly rounded to 0.
- (areAlmostEqual(aff.a11, 0.0) ? "0" : ::to_string(aff.a11, 5)) + "," +
- (areAlmostEqual(aff.a12, 0.0) ? "0" : ::to_string(aff.a12, 5)) + "," +
- (areAlmostEqual(aff.a13, 0.0) ? "0" : ::to_string(aff.a13, 5)) + "," +
- (areAlmostEqual(aff.a21, 0.0) ? "0" : ::to_string(aff.a21, 5)) + "," +
- (areAlmostEqual(aff.a22, 0.0) ? "0" : ::to_string(aff.a22, 5)) + "," +
- (areAlmostEqual(aff.a23, 0.0) ? "0" : ::to_string(aff.a23, 5));
+ // Note: toString distinguishes + and - 0. This is a problem when comparing
+ // aliases, so near-zero values are explicitly rounded to 0.
+ return (areAlmostEqual(aff.a11, 0.0) ? "0" : ::to_string(aff.a11, 5)) + "," +
+ (areAlmostEqual(aff.a12, 0.0) ? "0" : ::to_string(aff.a12, 5)) + "," +
+ (areAlmostEqual(aff.a13, 0.0) ? "0" : ::to_string(aff.a13, 5)) + "," +
+ (areAlmostEqual(aff.a21, 0.0) ? "0" : ::to_string(aff.a21, 5)) + "," +
+ (areAlmostEqual(aff.a22, 0.0) ? "0" : ::to_string(aff.a22, 5)) + "," +
+ (areAlmostEqual(aff.a23, 0.0) ? "0" : ::to_string(aff.a23, 5));
}
//-----------------------------------------------------------------------------------
@@ -68,7 +70,7 @@ std::string toString(SkVD *vd, double sdFrame) {
//-----------------------------------------------------------------------------------
std::string toString(const PlasticSkeleton::vertex_type &vx) {
- // TODO: Add z and rigidity
+ // TODO: Add z and rigidity support
return ::to_string(vx.P().x, 5) + " " + ::to_string(vx.P().y, 5);
}
@@ -121,10 +123,7 @@ TFx *PlasticDeformerFx::clone(bool recursive) const {
//-----------------------------------------------------------------------------------
bool PlasticDeformerFx::canHandle(const TRenderSettings &info, double frame) {
- // Yep. Affines are handled. Well - it's easy, since OpenGL lets you do that
- // directly
- // with a glPushMatrix...
-
+ // Affines are handled directly via OpenGL matrix pushes
return true;
}
@@ -159,8 +158,8 @@ bool PlasticDeformerFx::doGetBBox(double frame, TRectD &bbox,
const TRenderSettings &info) {
if (!m_port.isConnected()) return false;
- // It's hard work to calculate the bounding box of a plastic deformation.
- // Decline.
+ // Bounding box computation for plastic deformation is complex; return
+ // infinite rect
bbox = TConsts::infiniteRectD;
return true;
}
@@ -169,13 +168,10 @@ bool PlasticDeformerFx::doGetBBox(double frame, TRectD &bbox,
void PlasticDeformerFx::buildRenderSettings(double frame,
TRenderSettings &info) {
- // As previously pointed out, this fx is able to handle affines. We can,
- // actually, *decide*
- // the input reference to work with.
-
- // So, the best choice is to let the *input fx* decide the appropriate
- // reference, by invoking
- // its handledAffine() method.
+ // As previously noted, this FX is capable of handling affine transformations.
+ // Therefore, it can determine the most suitable input reference to work with.
+ // The best approach is to delegate this decision to the *input FX* itself,
+ // by calling its handledAffine() method to obtain the appropriate affine reference.
m_was64bit = false;
if (info.m_bpp == 64) {
m_was64bit = true;
@@ -190,7 +186,7 @@ bool PlasticDeformerFx::buildTextureDataSl(double frame, TRenderSettings &info,
TAffine &worldLevelToLevelAff) {
int row = (int)frame;
- // Initialize level vars
+ // Initialize level variables
TLevelColumnFx *lcfx = (TLevelColumnFx *)m_port.getFx();
TXshLevelColumn *texColumn = lcfx->getColumn();
@@ -201,32 +197,22 @@ bool PlasticDeformerFx::buildTextureDataSl(double frame, TRenderSettings &info,
if (!texSl || texSl->getType() == MESH_XSHLEVEL) return false;
- // Build dpi data
+ // Build DPI data
TPointD texDpi(texSl->getDpi(texFid, 0));
if (texDpi.x == 0.0 || texDpi.y == 0.0 || texSl->getType() == PLI_XSHLEVEL)
texDpi.x = texDpi.y = Stage::inch;
- // Build reference transforms data
-
- // NOTE: TAffine() corresponds to IMAGE coordinates here, not WORLD
- // coordinates. This is achieved
- // by removing the level's dpi affine during render-tree build-up (see
+ // Build reference transform data.
+ // NOTE: TAffine() here refers to IMAGE coordinates (not WORLD),
+ // achieved by removing level DPI affine during render-tree construction (see
// scenefx.cpp).
worldLevelToLevelAff = TScale(texDpi.x / Stage::inch, texDpi.y / Stage::inch);
- // Initialize input render settings
-
- // In the case of vector images, in order to retain the image quality required
- // by info.m_affine,
- // the scale component is allowed too.
-
- // In the raster image case, we'll use the original image reference IF the
- // affine is a magnification
- // (ie the scale is > 1.0) - OTHERWISE, the OpenGL minification filter is too
- // crude since it renders
- // a fragment using its 4 adjacent pixels ONLY; in this case, we'll pass the
- // affine below.
+ // Initialize input render settings.
+ // For vector images (PLI), allow full affine transform to preserve quality.
+ // For raster images, use original reference if scaling up (scale > 1.0).
+ // Otherwise, apply affine transform to avoid low-quality OpenGL minification.
const TAffine &handledAff = TRasterFx::handledAffine(info, frame);
@@ -237,7 +223,7 @@ bool PlasticDeformerFx::buildTextureDataSl(double frame, TRenderSettings &info,
info.m_affine = TAffine();
buildRenderSettings(frame, info);
- // NOTE: scale = handledAff.a11 / worldLevelToLevelAff.a11
+ // Apply scale if handled affine is minifying (scale < 1.0)
if (handledAff.a11 < worldLevelToLevelAff.a11)
info.m_affine =
TScale(handledAff.a11 / worldLevelToLevelAff.a11) * info.m_affine;
@@ -250,11 +236,9 @@ bool PlasticDeformerFx::buildTextureDataSl(double frame, TRenderSettings &info,
bool PlasticDeformerFx::buildTextureData(double frame, TRenderSettings &info,
TAffine &worldLevelToLevelAff) {
- // Common case (typically happen with sub-xsheets)
-
+ // Common case (e.g., sub-XSheets): adjust info and match reference
buildRenderSettings(frame, info); // Adjust the info
worldLevelToLevelAff = TAffine(); // Reference match
-
return true;
}
@@ -275,11 +259,11 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
if (dynamic_cast<TLevelColumnFx *>(m_port.getFx())) {
if (!buildTextureDataSl(frame, texInfo, worldTexLevelToTexLevelAff)) return;
- } else
+ } else {
buildTextureData(frame, texInfo, worldTexLevelToTexLevelAff);
+ }
- // Initialize mesh level vars
-
+ // Initialize mesh level variables
const TXshCell &meshCell = m_xsh->getCell(row, m_col);
TXshSimpleLevel *meshSl = meshCell.getSimpleLevel();
@@ -288,7 +272,6 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
if (!meshSl || meshSl->getType() != MESH_XSHLEVEL) return;
// Retrieve mesh image and deformation
-
TStageObject *meshColumnObj =
m_xsh->getStageObject(TStageObjectId::ColumnId(m_col));
@@ -296,22 +279,17 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
if (!mi) return;
// Retrieve deformation data
-
const PlasticSkeletonDeformationP &sd =
meshColumnObj->getPlasticSkeletonDeformation();
assert(sd);
double sdFrame = meshColumnObj->paramsTime(frame);
- // Build dpi data
-
+ // Build DPI data
TPointD meshDpi(meshSl->getDpi(meshFid, 0));
assert(meshDpi.x != 0.0 && meshDpi.y != 0.0);
- // Build reference transforms data
-
- // Build affines
-
+ // Build reference transforms
const TAffine &imageToTextureAff = texInfo.m_affine;
const TAffine &worldTexLevelToWorldMeshAff = m_texPlacement;
const TAffine &meshToWorldMeshAff =
@@ -323,7 +301,6 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
const TAffine &meshToTextureAff = imageToTextureAff * meshToTexLevelAff;
// Retrieve deformer data
-
TScale worldMeshToMeshAff(meshDpi.x / Stage::inch, meshDpi.y / Stage::inch);
std::unique_ptr<const PlasticDeformerDataGroup> dataGroup(
@@ -331,18 +308,18 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
sdFrame, mi.getPointer(), sd.getPointer(), sd->skeletonId(sdFrame),
worldMeshToMeshAff));
- // Build texture
-
// Build the mesh's bounding box and map it to input reference
TRectD meshBBox(meshToTextureAff * mi->getBBox());
- // Now, build the tile's geometry
+ // Build the tile's geometry
TRectD texBBox;
m_port->getBBox(frame, texBBox, texInfo);
+ // Use intersection (* operator) instead of union
TRectD bbox = texBBox * meshBBox;
if (bbox.getLx() <= 0.0 || bbox.getLy() <= 0.0) return;
+ // Align to pixel boundaries
bbox.x0 = tfloor(bbox.x0);
bbox.y0 = tfloor(bbox.y0);
bbox.x1 = tceil(bbox.x1);
@@ -350,38 +327,61 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
TDimension tileSize(tround(bbox.getLx()), tround(bbox.getLy()));
- // Then, compute the input image
+ // Compute the input image
TTile inTile;
m_port->allocateAndCompute(inTile, bbox.getP00(), tileSize, TRasterP(), frame,
texInfo);
- QOpenGLContext *context;
- // Draw the textured mesh
+
+ // Draw the textured mesh using the working approach
{
// Prepare texture
TRaster32P tex(inTile.getRaster());
- TRop::depremultiply(tex); // Textures must be stored depremultiplied.
- // See docs about the tglDraw() below.
+ TRop::depremultiply(tex);
static TAtomicVar var;
const std::string &texId = "render_tex " + std::to_string(++var);
- // Prepare an OpenGL context
- context = new QOpenGLContext();
+ // Use the working context creation approach
+ std::unique_ptr<QOpenGLContext> context(new QOpenGLContext());
+ context->moveToThread(QThread::currentThread());
+
+ // Share context with current if available
if (QOpenGLContext::currentContext())
context->setShareContext(QOpenGLContext::currentContext());
+
context->setFormat(QSurfaceFormat::defaultFormat());
- context->create();
- context->makeCurrent(info.m_offScreenSurface.get());
+
+ if (!context->create()) {
+ TSysLog::error("PlasticDeformerFx: Failed to create OpenGL context");
+ tile.getRaster()->clear();
+ return;
+ }
+
+ if (!context->makeCurrent(info.m_offScreenSurface.get())) {
+ TSysLog::error("PlasticDeformerFx: Failed to make context current");
+ tile.getRaster()->clear();
+ return;
+ }
TDimension d = tile.getRaster()->getSize();
QOpenGLFramebufferObject fb(d.lx, d.ly);
- fb.bind();
+ if (!fb.bind()) {
+ TSysLog::error("PlasticDeformerFx: Failed to bind FBO");
+ tile.getRaster()->clear();
+ return;
+ }
- // Load texture into the context
+ // Load texture
TTexturesStorage *ts = TTexturesStorage::instance();
const DrawableTextureDataP &texData = ts->loadTexture(texId, tex, bbox);
+ if (!texData) {
+ TSysLog::error("PlasticDeformerFx: Failed to load texture data");
+ fb.release();
+ tile.getRaster()->clear();
+ return;
+ }
- // Draw
+ // Set up OpenGL for rendering
glViewport(0, 0, d.lx, d.ly);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
@@ -392,12 +392,15 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
+
+ // Use the working transformation
tglMultMatrix(TTranslation(-tile.m_pos) * info.m_affine *
meshToWorldMeshAff);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
+ // Draw the mesh
tglDraw(*mi, *texData, meshToTextureAff, *dataGroup);
// Retrieve drawing and copy to output tile
@@ -434,19 +437,22 @@ void PlasticDeformerFx::doCompute(TTile &tile, double frame,
fb.release();
- // context->getRaster(tile.getRaster());
+ // Cleanup context->getRaster(tile.getRaster());
glFlush();
glFinish();
- // Cleanup
- // No need to disable stuff - the context dies here
+ // Unload texture to prevent memory leaks
+ // ts->unloadTexture(texId); // Auto-released ttexturesstorage??
+
+ context->doneCurrent();
+ }
- // ts->unloadTexture(texId); // Auto-released
- // due to display list destruction
- context->deleteLater();
- // context->doneCurrent();
+ // Verify no OpenGL errors
+ GLenum err = glGetError();
+ if (err != GL_NO_ERROR) {
+ TSysLog::warning("PlasticDeformerFx: OpenGL error after draw: " +
+ std::to_string(err));
}
- assert(glGetError() == GL_NO_ERROR);
}
//-----------------------------------------------------------------------------------
@@ -462,15 +468,16 @@ void PlasticDeformerFx::doDryCompute(TRectD &rect, double frame,
if (dynamic_cast<TLevelColumnFx *>(m_port.getFx())) {
if (!buildTextureDataSl(frame, texInfo, worldTexLevelToTexLevelAff)) return;
- } else
+ } else {
buildTextureData(frame, texInfo, worldTexLevelToTexLevelAff);
+ }
const TXshCell &meshCell = m_xsh->getCell(row, m_col);
TXshSimpleLevel *meshSl = meshCell.getSimpleLevel();
const TFrameId &meshFid = meshCell.getFrameId();
- if (!meshSl || meshSl->getType() == MESH_XSHLEVEL) return;
+ if (!meshSl || meshSl->getType() != MESH_XSHLEVEL) return;
TStageObject *meshColumnObj =
m_xsh->getStageObject(TStageObjectId::ColumnId(m_col));
@@ -497,13 +504,14 @@ void PlasticDeformerFx::doDryCompute(TRectD &rect, double frame,
// Build the mesh's bounding box and map it to input reference
TRectD meshBBox(meshToTextureAff * mi->getBBox());
- // Now, build the tile's geometry
+ // Build the tile's geometry
TRectD texBBox;
m_port->getBBox(frame, texBBox, texInfo);
TRectD bbox = texBBox * meshBBox;
if (bbox.getLx() <= 0.0 || bbox.getLy() <= 0.0) return;
+ // Align to pixel boundaries
bbox.x0 = tfloor(bbox.x0);
bbox.y0 = tfloor(bbox.y0);
bbox.x1 = tceil(bbox.x1);