Skip to content

Commit

Permalink
Fix density handling in Collision::ToElement
Browse files Browse the repository at this point in the history
A density element was written unconditionally,
even if it was not originally set by the user.
This checks the optional density value before setting
via ToElement().

Signed-off-by: Steve Peters <[email protected]>
  • Loading branch information
scpeters committed Jan 24, 2024
1 parent b41b48b commit 8d91b6a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Collision.cc
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ sdf::ElementPtr Collision::Element() const
return this->dataPtr->sdf;
}

/////////////////////////////////////////////////
sdf::ElementPtr Collision::ToElement() const
{
sdf::Errors errors;
Expand All @@ -377,8 +378,11 @@ sdf::ElementPtr Collision::ToElement(sdf::Errors &_errors) const
poseElem->Set<gz::math::Pose3d>(_errors, this->RawPose());

// Set the density
sdf::ElementPtr densityElem = elem->GetElement("density", _errors);
densityElem->Set<double>(this->Density());
if (this->dataPtr->density.has_value())
{
sdf::ElementPtr densityElem = elem->GetElement("density", _errors);
densityElem->Set<double>(this->Density());
}

// Set the geometry
elem->InsertElement(this->dataPtr->geom.ToElement(_errors), true);
Expand Down
15 changes: 15 additions & 0 deletions src/Collision_TEST.cc
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,8 @@ TEST(DOMCollision, ToElement)

sdf::ElementPtr elem = collision.ToElement();
ASSERT_NE(nullptr, elem);
// Expect no density element
EXPECT_FALSE(elem->HasElement("density"));

sdf::Collision collision2;
collision2.Load(elem);
Expand All @@ -435,6 +437,19 @@ TEST(DOMCollision, ToElement)
ASSERT_NE(nullptr, surface2->Friction());
ASSERT_NE(nullptr, surface2->Friction()->ODE());
EXPECT_DOUBLE_EQ(1.23, surface2->Friction()->ODE()->Mu());

// Now set density in collision
const double kDensity = 1234.5;
collision.SetDensity(kDensity);
sdf::ElementPtr elemWithDensity = collision.ToElement();
ASSERT_NE(nullptr, elemWithDensity);
// Expect density element
ASSERT_TRUE(elemWithDensity->HasElement("density"));
EXPECT_DOUBLE_EQ(kDensity, elemWithDensity->Get<double>("density"));

sdf::Collision collision3;
collision3.Load(elem);
EXPECT_DOUBLE_EQ(kDensity, collision.Density());
}

/////////////////////////////////////////////////
Expand Down

0 comments on commit 8d91b6a

Please sign in to comment.