03
Oct 11

Developing a Vectorworks 2011 tool plug-in, TDD-style – Episode 4

Now that we’re able to create real Vectorworks geometry with our tool, what’s next? The “spec” laid out in Episode 0 calls for creating a red or green line depending on where the user sets the clicks. Tackling the click’s location test first sounds like an interesting challenge.

What’s the simplest way to start? If the user doesn’t click on a polygon object, our tool should ignore the clicks. How does RedGreenLineTool know if the clicks happen on a polygon object? For know, we let it know by calling MouseOverPolygonObject() before adding tool points. Sounds reasonable.

TEST_N(ToolPointsShouldBeReflectedAsStartEndPointOfLineObject)
{
	MockRedGreenLineTool vwTool;
	vwTool.MouseOverPolygonObject();
	
	vwTool.AddPoint(WorldPt3(0, 0, 0));
	vwTool.AddPoint(WorldPt3(50, 0, 0));

	CHECK_EQUAL(2, vwTool.GetNumToolPoints());
}

If we don’t call MouseOverPolygonObject() before adding points, they shouldn’t be added to the list of points tracked.

TEST_N(ToolPointNotOnPolygonShouldBeIgnored)
{
	MockRedGreenLineTool vwTool;
	
	vwTool.AddPoint(WorldPt3(0, 0, 0));
	vwTool.AddPoint(WorldPt3(50, 0, 0));
	
	CHECK_EQUAL(0, vwTool.GetNumToolPoints());
}

Implementation, of course, is rather trivial (for now ;-). We just add a bool fMockMouseOverPolygonObject to MockRedGreenLineTool, set it MouseOverPolygonObject(), test it in AddPoint() and we’re done.

Well, not really. We do have an implementation for MockRedGreenLineTool only, we need to move the implementation up the inheritance tree to RedGreenLineTool to turn it into something useful.

class RedGreenLineTool {

	virtual bool IsMouseOverPolygonObject() = 0;

	void AddPoint(const WorldPt3& p) {
		if (IsMouseOverPolygonObject())
			fToolPoints.PushData(p);
	}
};

Implementation of IsMouseOverPolygonObject() is rather trivial for MockRedGreenLineTool, we just return fMockMouseOverPolygonObject. Of course, VectorworksRedGreenLineTool needs a more sophisticated implementation, but (as intended) a rather simple one:

class VectorworksRedGreenLineTool {

	virtual bool IsMouseOverPolygonObject() {
		MCObjectHandle overObject = NULL;
		short overPart;
		long code;
		gSDK->TrackTool(overObject, overPart, code);
	
		return (overObject && ! VWPolygon2DObj::IsPolygon2DObject(overObject));
	}
};

Now this rather straightforward implementation doesn’t quite work yet, as this code doesn’t reflect the state Vectorworks is in. every mouse click is registered by Vectorworks first, then an event is sent to the tool to process it. If we choose to ignore the mouse click, we need to notify Vectorworks of this fact. Thus, we need to make some minor changes to the code to accommodate for this behavior.

class RedGreenLineTool {

	virtual void PopLastToolPoint() = 0;

	void AddPoint(const WorldPt3& p) {
		if (IsMouseOverPolygonObject())
			fToolPoints.PushData(p);
		else
			PopLastToolPoint();
	}
};

While MockRedGreenLineTool gets away with an empty implementation for PopLastToolPoint(), VectorworksRedGreenLineTool needs to notify Vectorworks that the last tool point registered should be removed:

class VectorworksRedGreenLineTool {

	virtual void PopLastToolPoint() {
		gSDK->PopLastToolPt();
	}
};

Where are we at? We do have a basic implementation of mouse tracking in place. RedGreenLineTool is able to tell if the mouse is over a polygon object while the mouse is clicked. In the next episode, we will tackle tracking mouse clicks on a single or two different polygons in order to create red or green lines.

Previous Episode


22
Jul 11

Developing a Vectorworks 2011 tool plug-in, TDD-style – Episode 3

With quite a sound class structure in place (and after returning from a refreshing summer vacation in Turkey), let’s see if we can put our new class strcuture to good use while trying to create the actual Vectorworks geometry (a line), test first – of course. Reading through the first series on TDD with Vectorworks, we used a model object for representing the geometric properties of the object and a rather thin layer to create the actual Vectorworks geometry from the model. How about trying this approach with a Vectorworks tool plug-in, too?

TEST_N(ToolPointsShouldBeReflectedAsStartEndPointOfLineObject)
{
	MockRedGreenLineTool vwTool;

	vwTool.AddPoint(WorldPt3(0, 0, 0));
	vwTool.AddPoint(WorldPt3(50, 0, 0));

	MockRedGreenLineObject* vwObject = vwTool.Create();
	
	CHECK_EQUAL(WorldPt3(0, 0, 0), vwObject->GetStartPoint());
	CHECK_EQUAL(WorldPt3(50, 0, 0), vwObject->GetEndPoint());
	
	delete vwObject;
}

We expect that the tool object will be able to create the line object for us and that the tool will take care of making sure that the start & end point of the line object will reflect the tool points.

In order to get the test to compile, we need to implement Create() for MockRedGreenLineTool.

class MockRedGreenLineTool : public RedGreenLineTool {

public:

	MockRedGreenLineObject* Create() const {
		MockRedGreenLineObject* lineObject = new MockRedGreenLineObject();

		lineObject->SetStartPoint(fToolPoints[0].fPoint);
		lineObject->SetEndPoint(fToolPoints[1].fPoint);

		return lineObject;
	}		

};

Now we need to come up with a simple implementation for MockRedGreenLineObject. Not a lot to see here – just a mock implementation.

class MockRedGreenLineObject {

public:
	
	void SetStartPoint(const WorldPt3& p) {
		fStartPoint = p;
	}
	
	void SetEndPoint(const WorldPt3& p) {
		fEndPoint = p;
	}
	
	virtual WorldPt3 GetStartPoint() const {
		return fStartPoint;
	}
	
	virtual WorldPt3 GetEndPoint() const {
		return fEndPoint;
	}
	
private:
	
	WorldPt3 fStartPoint;
	WorldPt3 fEndPoint;
};

Now the code compiles, links and the test passes. As in episode 1, the code is stuck in the “Mock” classes, but we need to drive it from Vectorworks. Let’s refactor us out of this mess.

First, we push the implementation of Create() up to the base class, RedGreenLineTool. However, RedGreenLineTool::Create() shouldn’t return an instance of MockRedGreenLineObject, but an instance of a more generic RedGreenLineObject class in order to accommodate creation of a Vectorworks-specific subclass. Creation of the particular instance is left to the subclasses of RedGreenLineTool.

We move the code from MockRedGreenLineObject to a new superclass RedGreenLineObject.

class RedGreenLineObject {

public:
	
	void SetStartPoint(const WorldPt3& p) {
		fStartPoint = p;
	}
	
	void SetEndPoint(const WorldPt3& p) {
		fEndPoint = p;
	}
	
	virtual WorldPt3 GetStartPoint() const {
		return fStartPoint;
	}
	
	virtual WorldPt3 GetEndPoint() const {
		return fEndPoint;
	}

private:
	
	WorldPt3 fStartPoint;
	WorldPt3 fEndPoint;
};

Code still compiles, links and passes the tests. Now for the surgery concerning RedGreenLineTool::Create():

class VectorworksRedGreenLineTool : public RedGreenLineTool {

	RedGreenLineObject* CreateRedGreenLineObject() const {
		return VectorworksRedGreenLineObject();
	}
};


class MockRedGreenLineTool : public RedGreenLineTool {

	RedGreenLineObject* CreateRedGreenLineObject() const {
		return MockRedGreenLineObject();
	}
};


class RedGreenLineTool {

public:

	RedGreenLineObject* CreateRedGreenLineObject() const = 0;

	RedGreenLineObject* Create() const {
		RedGreenLineObject* lineObject = CreateRedGreenLineObject();

		lineObject->SetStartPoint(fToolPoints[0].fPoint);
		lineObject->SetEndPoint(fToolPoints[1].fPoint);

		return lineObject;
	}		

};

Again, code compiles, links and our tests pass. What’s left? We need to hook up the classes to CTool_EventSink and create the Vectorworks geometry.

long CTool_EventSink::LegacyMain(long action, long message1, long message2)
{
	long result = 0;
	
	switch (action) {

		case kToolHandleComplete:
			fRedGreenLineTool->Create();
			break;
	}
};

Compiles, links. No surprises here. We start Vectorworks, select our tool, click twice to create a line – but nothing happens….yet. Ah, we forgot to create the geometry. How to do that? Here’s the simplest way of doing it which comes to my mind:

class RedGreenLineTool {

public:

	RedGreenLineObject* Create() const {
		RedGreenLineObject* lineObject = CreateRedGreenLineObject();

		lineObject->SetStartPoint(fToolPoints[0].fPoint);
		lineObject->SetEndPoint(fToolPoints[1].fPoint);

		lineObject->CreateGeometry();

		return lineObject;
	}		

};

Of course, the implementation of CreateGeometry() in MockRedGreenLineObject will be empty, whereas VectorworksRedGreenLineObject::CreateGeometry() is somewhat beefier:

class VectorworksRedGreenLineObject {

	virtual void CreateGeometry() {
		VWLine2DObj line(fStartPoint.x, fStartPoint.y, fEndPoint.x, fEndPoint.y);
		line.AddObjectToContainer(gSDK->GetDefaultContainer());
	}

};

We can easily deal with the non-testability of CreateGeometry(), as all the logic of the line object’s “model” itself is under test. And if something goes horribly wrong in CreateGeometry(), it should be easy to figure out.

RedGreenLineObject doesn’t feature an awful lot of sophisticated logic so far, but we are not done yet. The “spec” calls for creating a red or green line depending on where the user sets the clicks. Sounds like this attribute will find a good home in the RedGreenLineObject class. Speaking of it, determining the location of the clicks test first sounds like an interesting challenge. Let’s try to tackle that one in the next episode.

Previous Episode | Next Episode


17
Jun 11

Developing a Vectorworks 2011 tool plug-in, TDD-style – Episode 2

With a basic mock implementation of the tool point collecting part of a Vectorworks tool under our belt, let’s try to connect this class to a “real” Vectorworks tool event sink.

Using the MockRedGreenLineTool from within a CTool_EventSink doesn’t sound quite right. After all it’s supposed to be a mock implementation. We need to use a real tool implementation in the CTool_EventSink. Let’s do some restructuring to accomplish that. First, create a new class RedGreenLineTool with the code from MockRedGreenLineTool.

class RedGreenLineTool {
	
public:
	
	virtual ~RedGreenLineTool() {
	}

 	void AddPoint(const WorldPt3& p) {
		fToolPoints.PushData(p);
	}	

	virtual void PopPoint() {
		fToolPoints.PopData();
	}

	short GetNumToolPoints() const {
		return fToolPoints.NumItems();
	}
	
	TSmallArray<WorldPt3> fToolPoints;

};

Now, make MockRedGreenLineTool a subclass of RedGreenLineTool:

class MockRedGreenLineTool : public RedGreenLineTool {
}

and create VectorworksRedGreenLineTool, which is also a subclass of RedGreenLineTool.

class VectorworksRedGreenLineTool : public RedGreenLineTool {
}

This sure looks better to our TDD newbie eye. We have a common implementation for both the MockRedGreenLineTool used for testing and a VectorworksRedGreenLineTool used to connect the code to Vectorworks. Running the tests shows we didn’t break anything. Now we are able to use VectorworksRedGreenLineTool in a VWToolDefaultLine_EventSink implementation:

long CTool_EventSink::LegacyMain(long action, long message1, long message2)
{
	long result = 0;
	
	switch (action) {

		case kToolDoSetup:
			result = VWToolDefaultLine_EventSink::LegacyMain(action, message1, message2);
			
			fRedGreenLineTool = new VectorworksRedGreenLineTool();
			break;
			
		case kToolDoSetDown:
			result = VWToolDefaultLine_EventSink::LegacyMain(action, message1, message2);

			if (fRedGreenLineTool)
				delete fRedGreenLineTool;
			fRedGreenLineTool = NULL;
			break;
			
		case kToolPointAdded: {

			WorldPt3 toolPoint;
			if (gSDK->GetToolPt3D(gSDK->GetNumToolPts() - 1, toolPoint))
				fRedGreenLineTool->AddPoint(toolPoint);
			break;
		}
			
		case kToolPointRemoved:
			fRedGreenLineTool->PopPoint();
			break;
			
		default:
			result = VWToolDefaultLine_EventSink::LegacyMain(action, message1, message2);
			break;

	}
	
	return result;
}

Using the debugger, we are able to verify that everything is working out as expected.

Not a lot of functional but structural code changes in this episode, but we ended up with a class hierarchy which hints at things to come. We expect to push code common between the mock and Vectorworks implementation of the tool up the class hierarchy and code specific to the mock or Vectorworks implementation of the tool in the subclasses.

Let’s see how this class hierarchy holds up in the next episode when we tackle creating a line – test first, of course.

Previous Episode | Next Episode


08
Jun 11

Developing a Vectorworks 2011 tool plug-in, TDD-style – Episode 1

In Episode 0, we set the goal for this series: To develop a Vectorworks plug-in tool which creates a green line if both clicks are on the same Vectorworks polygon and creates a red line if the clicks are on two different polygons.

We will be using a slightly modified version of CppUnitLite2, for more details on how the testing targets are integrated in the Xcode projects please refer to Episode 0 of the plug-in object series.

As in our plug-in object series, the first challenge is “How do we start”?

As our tool will require two clicks, we may get away with subclassing VWToolDefaultLine_EventSink to implement the interactive behavior of the tool. Of course, we won’t be able to use a VWToolDefaultLine_EventSink in our testing target, as the testing environment runs as a separate application. So we need to come up with our own “Vectorworks tool” class. Let’s do that and see were it leads us.

What to test first? Our tool will be collecting up to two clicks (“tool points” in Vectorworks SDK lingo). Upon initialization, there are no tool point in the collection:

#include &quot;CppUnitLite2.h&quot;

TEST_N(ToolObjectShouldHaveNoPointsUponInitialization)
{
	MockRedGreenLineTool vwTool;

	CHECK_EQUAL(0, vwTool.GetNumToolPoints());
}

Not an awful lot of sophistication here, but we sure know how to make this test pass (doing the simplest thing that could possibly work):

class MockRedGreenLineTool {
	
public:
	
	short GetNumToolPoints() const {
		return 0;
	}
	
};

Compiles, links and even passes the test. Excellent. We’re off to a great start. Now for some more, ahm, sophistication. The tool should store the tool points (to create the line later on – we have no clue yet how to do that in a test-first fashion, but let’s just follow our chosen path of rather trivial steps for a while):

#include &quot;CppUnitLite2.h&quot;

TEST_N(ToolObjectShouldRememberToolPoints)
{
	MockRedGreenLineTool vwTool;
	
	vwTool.AddPoint(WorldPt3(0, 0, 0));
	vwTool.AddPoint(WorldPt3(50, 0, 0));
	
	CHECK_EQUAL(2, vwTool.GetNumToolPoints());
}

Making this test pass is no challenge either (even for a small mind like me):

class MockRedGreenLineTool {
	
public:
	
 	void AddPoint(const WorldPt3&amp; p) {
		fToolPoints.PushData(p);
	}	

	short GetNumToolPoints() const {
		return fToolPoints.NumItems();
	}
	
	TSmallArray&lt;WorldPt3&gt; fToolPoints;

};

Now that we’re on a roll, let’s add one more “event” to our class, removing tool points. Users will be able to back out of a Vectorworks tool step by step by removing the last tool point added.

TEST_N(ToolObjectPoppingToolPoints)
{
	MockRedGreenLineTool vwTool;
	
	vwTool.AddPoint(WorldPt3(0, 0, 0));
	vwTool.AddPoint(WorldPt3(50, 0, 0));
	
	CHECK_EQUAL(2, vwTool.GetNumToolPoints());

	vwTool.PopPoint();

	CHECK_EQUAL(1, vwTool.GetNumToolPoints());

	vwTool.PopPoint();

	CHECK_EQUAL(0, vwTool.GetNumToolPoints());
}

Luckily, TSmallArray features a method to remove the last entry added, so making the test pass is straightforward:

class MockRedGreenLineTool {
	
public:

	virtual void PopPoint() {
		fToolPoints.PopData();
	}

	// ...
	
};	

Where are we at? We now have a tool class collecting tool points (with the added bonus of being able to remove those tool points later). There are three questions which come to our mind:

  • We need to somehow connect MockRedGreenLineTool to the VWToolDefaultLine_EventSink
  • MockRedGreenLineTool needs to be able to know about the clicks being on a polygon
  • MockRedGreenLineTool needs to create a “red or green line object”

Let’s try to tackle connecting MockRedGreenLineTool to VWToolDefaultLine_EventSink in the next episode.

Previous EpisodeNext Episode


02
Jun 11

Developing a Vectorworks 2011 tool plug-in, TDD-style – Episode 0

In the epilogue of “Developing a Vectorworks 2011 plug-in object, TDD style”, I hinted at some not yet coherent thoughts on how to develop a Vectorworks plug-in tool test first. Creating some Vectorworks geometry test first was reasonably straightforward: Do all calculations in a separate model class and use the pre-calculated model to generate the Vectorworks geometry.

A Vectorworks tool is a more sophisticated problem for a small mind like yours truly: It interacts with the drawing in a series of clicks, objects may be tracked while tool is running etc. How do we capture this potentially rich interaction test-first? Before we tackle these questions, let’s describe the tool, code named “Red/Green Line Tool”:

As the name implies, it will collect two clicks in the document and draw a green line if the start- and endpoint of the line (the first & second “click”) are are on a 2D polygon. If the clicks aren’t on a 2D polygon, they should be ignored. To top things off, a red line should be drawn if the startpoint is located on a different 2D-polygon than the endpoint:

Redgreen

My goal is neither to cover all bases with the tests (I intend to leave those as an exercise for the reader ;-) nor to develop a shippable, fully Vectorworks-conform tool (my day job takes care of this desire), but to focus on these three questions:

  • How do I isolate the “interactiveness” of the tool in a testable class?

  • How do I isolate & test the creation of Vectorworks geometry?
  • How do the chosen tests drive the design & architecture of the code?

Tune in next week when you’ll hear Dr. Bob wondering about how to get this thing off the ground.

Episodes so far:


02
May 11

Developing a Vectorworks 2011 Plug-in, TDD-style – Epilogue

The code

[Update: I have posted an Xcode 4.6 / Visual Studio 2010 project for Vectorworks 2013 here.]

Please download the Xcode 3.2.3 project including all the sources here – SimpleCabinet.zip. The folder SimpleCabinet should be dropped into Vectorworks 2011 SDK’s Sources folder, like this:

The project features two targets, a testing target named “CppUnitLite2″ and the plug-in module shared library target, which outputs to /Applications/Vectorworks2011/Plug-ins. You will notice that all classes plus tests are contained in ExtObject.cpp. I’m doing this for small spikes – in real life, I would put each class in a separate file, no code in the header file etc.

The code features additional tests, refactorings and more usage of VWFC in SimpleCabinetCreator.

I haven’t gotten around to preparing & cleaning up the Visual Studio project of the Simple Cabinet project. Make sure to bug me so I feel obliged to release it, too.

Summary

It’s possible to create VectorWorks plug-in objects via TDD. In fact, it’s desirable: Developing the code test-first gave us a very nice separation between the testable model and a very thin layer creating the actual Vectorworks geometry. The SDK stubs (which exist, at this point, for the sole purpose of satisfying the linker) allow us to have a separate testing target and to mix testing code and non-testing code freely.

I found that it’s also possible to develop Vectorworks Layoutmanager-based dialogs (either straight ISDK or VWUI-based) in a strict TDD fashion, but that’s another series of posts waiting to be written and code / project files waiting to be cleaned up.

Wether it’s possible to develop Vectorworks tools in a test-driven fashion remains to be seen (although I’m pretty optimistic that it can be done quite nicely). I do have some thoughts on this matter but they aren’t coherent yet.

If you have any feedback regarding this series, please do not hesitate to post comments on the episodes, or contact me at hm dot kern at extragroup dot de, on Twitter or Facebook. I look forward to hearing from you.

Episodes


27
Apr 11

Developing a Vectorworks 2011 Plug-in, TDD-style – Episode 7

Now that we’re able to place a grid of front tiles / segments, the only thing left is the placement of the right / top blind front panels – if the front tiles don’t fit properly. As always, we’re starting with a very basic test. The right blind front (if there’s one) will be placed on the bottom board, therefore start at z == SimpleCabinetModel::kBoardThickness.

TEST_N(FrontModelRightBlindFront)
{
	SimpleCabinetModel simpleCabinet(2 * 200 + 2 * SimpleCabinetModel::kBoardThickness + 50, 
									 3 * 150 + 2 * SimpleCabinetModel::kBoardThickness + 70, 800);
	
	FrontModel frontModel(simpleCabinet.GetFrontModelOrigin(), simpleCabinet.GetFrontWidth(), simpleCabinet.GetFrontHeight());
	
	CHECK_EQUAL(SimpleCabinetModel::kBoardThickness, frontModel.GetRightZBlindFront());
}

Well, you could see that one coming, making the test pass is rather trivial – but it gets us on the track to more sophisticated functionality.

	WorldCoord GetRightZBlindFront() const {
		return fOrigin.z;
	}

Let’s add another check to the test. The height of the right blind front should be the height of the front model.

	CHECK_EQUAL(3 * 150 + 70, frontModel.GetRightBlindFrontHeight());

Quite obvious and should be easy to implement. There’s already an instance variable fHeight in the FrontModel:

	WorldCoord frontModel.GetRightBlindFrontHeight() const {
		return fHeight;
	}

The third component needed to generate the geometry for the right blind front model is the base rectangular shape for the extrude. Another check for our test.

	CHECK_EQUAL(WorldRect(SimpleCabinetModel::kBoardThickness + frontModel.GetNumColumns() * FrontModel::kSegmentWidth, 
						  FrontModel::kSegmentDepth,
						  SimpleCabinetModel::kBoardThickness + simpleCabinet.GetFrontWidth(), 0), 
				frontModel.GetRightBlindFrontBase());

Introducing two additional constants for the tile/segment’s width and depth, making the test pass requires a few lines of code:

class FrontModel {

	WorldRect GetRightBlindFrontBase() const {
		WorldCoord xStart = fOrigin.x + GetNumColumns() * kSegmentWidth;
		WorldCoord xEnd = fOrigin.x + fWidth;
		
		WorldRect r(0, 0, 0, 0);
		if (xStart != xEnd)
			r.Set(xStart, kSegmentDepth, xEnd, 0);

		return r;
	}
};

The top blind front is tackled the same way – We need it’s z position, it’s x dimensions and it’s height. Not an awful lot to see there. Now let’s check if we’re able to generate Vectorworks geometry with this model.

	void CreateFrom(const FrontModel& frontModel) {
		
		// ...

		WorldRect topBlindFrontBase = frontModel.GetTopBlindFrontBase();
		if (topBlindFrontBase != WorldRect(0, 0, 0, 0)) {
			MCObjectHandle topBlindFront = gSDK->CreateExtrude(frontModel.GetTopZBlindFront(), frontModel.GetTopZBlindFront() + frontModel.GetTopBlindFrontHeight());
			gSDK->AddObjectToContainer(gSDK->CreateRectangle(frontModel.GetTopBlindFrontBase()), topBlindFront);
		}
		
		WorldRect rightBlindFrontBase = frontModel.GetRightBlindFrontBase();
		if (rightBlindFrontBase != WorldRect(0, 0, 0, 0)) {
			MCObjectHandle rightBlindFront = gSDK->CreateExtrude(frontModel.GetRightZBlindFront(), frontModel.GetRightZBlindFront() + frontModel.GetRightBlindFrontHeight());
			gSDK->AddObjectToContainer(gSDK->CreateRectangle(frontModel.GetRightBlindFrontBase()), rightBlindFront);
		}
		

In fact, we are:

Episode 7

Tune in next weeks when you hear Dr. Bob say: “Let’s sum it up, post the code and I’m outta here”.

Previous Episode | Next Episode


24
Apr 11

Developing a Vectorworks 2011 Plug-in, TDD-style – Episode 6

We left off in Episode 5 trying to avoid Dr. Bob hitting us with a rolled-up newspaper as we forgot to account for the front tiles’s z position. Let’s see if we can fix this. First, we change the test for the front model origin to expect a WorldPt3 which, obviously, does contain a z-component.

TEST_N(FrontModelOrigin)
{
	SimpleCabinetModel simpleCabinet(600, 720, 800);
	
	FrontModel frontModel(simpleCabinet.GetFrontModelOrigin());
	
	CHECK_EQUAL(WorldPt3(SimpleCabinetModel::kBoardThickness, 0, SimpleCabinetModel::kBoardThickness), frontModel.GetOrigin());
}

Making this test pass requires a series of simple changes to FrontModel.

class FrontModel {

public:

	FrontModel(const WorldPt3& origin) :
		fOrigin(origin) {
	}

	WorldPt3 GetOrigin() const {
		return fOrigin;
	}

private:

	WorldPt3 fOrigin;
}

After making these changes gcc tells us that we should probably fix the tests FrontModelPositionOfFirstSegment and FrontModelPositionOfSecondSegment in order to make this thing compilable again. As in FrontModelOrigin, this requires us to replace WorldPt with WorldPt3 and we’re basically done.

With this out of the way, let’s concentrate on generalizing our FrontModel. So far, we’re able to calculate the position of the first and second segment / tile (assuming both fit into the cabinet). Looking at the screenshot in episode 0, it sure looks like the front tiles should be arranged in rows & columns. Let’s see if we can work towards this. How about computing the number of front tile rows & columns which “fit” into a given cabinet? Let’s start with a simple test – if the cabinet is too small, no front tiles will fit at all.

TEST_N(FrontModelNoRowsNoColumnsNotWideEnough)
{
	SimpleCabinetModel simpleCabinet(150, 720, 800);
	
	FrontModel frontModel(simpleCabinet.GetFrontModelOrigin(), 
						  simpleCabinet.GetFrontWidth(), 
						  simpleCabinet.GetFrontHeight());
	
	CHECK_EQUAL(0, frontModel.GetNumRows());
	CHECK_EQUAL(0, frontModel.GetNumColumns());
}

In order to be able to compute the number of rows & columns, we have to supply the FrontModel with the space available for placing front tiles. So, we need tests to for these functions. Let’s #if 0 the last test for a moment and write new tests for GetFrontWidth() and GetFrontHeight().

TEST_N(SimpleCabinetFrontWidthHeight)
{
	SimpleCabinetModel simpleCabinet(600, 720, 800);

	CHECK_EQUAL(600 - 2 * SimpleCabinetModel::kBoardThickness, 
				simpleCabinet.GetFrontWidth());
	CHECK_EQUAL(720 - 2 * SimpleCabinetModel::kBoardThickness, 
				simpleCabinet.GetFrontHeight());
}

Let’s make this test pass.


class SimpleCabinetModel {

public:
	
	WorldCoord GetFrontWidth() const {
		return fWidth - 2 * kBoardThickness;
	}
	
	WorldCoord GetFrontHeight() const {
		return fHeight - 2 * kBoardThickness;
	}
};

Backtracking to our test FrontModelNoRowsNoColumnsNotWideEnough, we change FrontModel‘s constructor (again).

class FrontModel {

public:
	
	FrontModel(const WorldPt3& origin, WorldCoord width, WorldCoord height) : 
		fOrigin(origin), fWidth(width), fHeight(height) {
	}
};

What was our intital goal? Ah, computing the number of rows & columns (in order to make the test pass). Well, that’s straightforward:

class FrontModel {

public:
	
	long GetNumRows() const {
		return 0;
	}
	
	long GetNumColumns() const {
		return 0;
	}
};

Indeed, it’s pretty straightforward for the test we’re trying to make pass. We just write enough code to make the test pass. And returning 0 makes the test pass. Let’s move on to the next test.

TEST_N(FrontModelThreeRowsTwoColumnsFits)
{
	SimpleCabinetModel simpleCabinet(2 * 200 + 2 * SimpleCabinetModel::kBoardThickness, 
									 3 * 150 + 2 * SimpleCabinetModel::kBoardThickness, 
									 800);
	
	FrontModel frontModel(simpleCabinet.GetFrontModelOrigin(), 
						  simpleCabinet.GetFrontWidth(), 
						  simpleCabinet.GetFrontHeight());
	
	CHECK_EQUAL(3, frontModel.GetNumRows());
	CHECK_EQUAL(2, frontModel.GetNumColumns());
}

Now is the right time to flesh out GetNumRows() and GetNumColumns().

class FrontModel {

public:
	
	long GetNumRows() const {
		return MyMathUtils::fdiv(fHeight, SimpleCabinetModel::kSegmentHeight);
	}
	
	long GetNumColumns() const {
		return MyMathUtils::fdiv(fWidth, SimpleCabinetModel::kSegmentWidth);
	}
};	

In order to get the number of front tiles fitting into a row, we need to divide the overall width available for the front tiles and divide it (as in division of integers) by the width of a segment. Same for the number of front tiles fitting into a column.

Where are we at? We now have code for calculating the number of tiles in x direction (columns) and z direction (rows). If we would have a function computing the x, y & z position of a front tile at a given row & column we could certainly beef up SimpleCabinetCreator::CreateFrom() with a nice loop placing all the front tiles. Let’s write a test for this function computing a tiles position:

TEST_N(FrontModelPositionOfARowColumn)
{
	SimpleCabinetModel simpleCabinet(1200, 720, 800);
	
	FrontModel frontModel(simpleCabinet.GetFrontModelOrigin(), 
						  simpleCabinet.GetFrontWidth(), 
						  simpleCabinet.GetFrontHeight());

	WorldPt3 expectedPosition = frontModel.GetOrigin() +
								WorldPt3(3 * SimpleCabinetModel::kSegmentWidth, 0, 
										 2 * SimpleCabinetModel::kSegmentHeight)
	CHECK_EQUAL(expectedPosition, 
				frontModel.GetSegmentPosition(3, 2));
}

Here’s the code to make the test pass:

class FrontModel {

public:
	
	WorldPt3 GetSegmentPosition(long column, long row) const
	{
		WorldPt3 position(GetOrigin());
		
		position += WorldPt3(column * fSegmentWidth, 
							 0,
							 row * fSegmentHeight);
		
		return position;
	}
};

And for the grand final of this episode, let’s tackle placing the front tile symbols in SimpleCabinetCreator::CreateFrom(). With the preparatory work we’ve done in this episode it should be pretty straightforward – and it is:

	
	void CreateFrom(const FrontModel& frontModel) {
		
		for (long i = 0; i  frontModel.GetNumColumns(); i++) 
			for (long j = 0; j < frontModel.GetNumRows(); j++) {
				VWObject frontSegment = gSDK->PlaceSymbolByNameN(frontModel.GetFrontSymbolName(), WorldPt(0, 0));
				frontSegment.MoveObject3D(frontModel.GetSegmentPosition(i, j)); 
				fSimpleCabinet.AddObject(frontSegment);
			}	
	}

Episode 6

Tune in next week when you hear Nurse Piggy say: “Are we done yet? I have a date with a certain frog for dinner… “.

Previous Episode | Next Episode


21
Apr 11

Developing a Vectorworks 2011 Plug-in, TDD-style – Episode 5

In Episode 4 we finally saw the fruits of our labor – TDD-style. What’s left? We need to come up with some code for the front tiles / segments.

Let’s get right to it. Here the first test. We assume that there’s class FrontModel with a method GetOrigin(), which returns the position of the leftmost bottom front tile.

TEST_N(FrontModelPositionOfFirstSegment)
{
	SimpleCabinetModel simpleCabinet(600, 720, 800);
	
	FrontModel frontModel;
	simpleCabinet.GetFrontModel(frontModel);
	
	CHECK_EQUAL(WorldPt(SimpleCabinetModel::kBoardThickness, 0), 
				frontModel.GetOrigin());
	
}

This is another one of these “Get’s us going” tests. Not an awful lot of thought need to make it pass, but it puts us in the right mood for the next challenge.


class SimpleCabinetModel {
	
public:
	
	// ...

	void GetFrontModel(FrontModel& model) const {
		model.SetOrigin(WorldPt(kBoardThickness, 0));
	}
};	


class FrontModel {
	
public:
	
	FrontModel() : fOrigin(WorldPt (0, 0)) {
	}
	
	WorldPt GetOrigin() {
		return fOrigin;
	}
	
	void SetOrigin(const WorldPt& origin) {
		fOrigin = origin;
	}
	
private:
	
	WorldPt fOrigin;
	
};

What’s next? Look at the “spec” in Episode 0, it looks like the front tiles are made of rows and columns – but let’s not jump to conclusions yet. Dr. Bob is just a quack, not a CS major. The next simple test which comes to our mind is checking for the position of the second front tile – which should be located to the right of the first front tile (we assume that both tiles fit into the cabinet, of course).

TEST_N(FrontModelPositionOfSecondSegment)
{
	SimpleCabinetModel simpleCabinet(600, 720, 800);
	
	FrontModel frontModel;
	simpleCabinet.GetFrontModel(frontModel);
	
	CHECK_EQUAL(frontModel.GetOrigin() + WorldPt(SimpleCabinetModel::kSegmentWidth, 0), 
				frontModel.GetPositionOfSecondSegment());
}

In order to calculate the second tiles position, we need the width of a front tile. For now, we’re accessing SimpleCabinetModel::kSegmentWidth from FrontModel::GetPositionOfSecondSegment() for this purpose.

	WorldPt GetPositionOfSecondSegment() const {
		return fOrigin + WorldPt(SimpleCabinetModel::kSegmentWidth, 0);
	}

Doesn’t feel absolutely right yet, but we’re confident that this will be smoothed out over the next tests & episodes.

After the raving success with SimpleCabinetCreator in Episode 4, let’s see if we can create the Vectorworks geometry for the first & second tile before continuing our journey fleshing out the FrontModel. We have the uneasy feeling that The reason why

Let’s start with the plug-in object’s Recalculate() function. We spice up SimpleCabinetCreator a bit, as we need access to both the SimpleCabinetModel and FrontModel. Asking SimpleCabinetModel to “fill in the blanks” in FrontModel didn’t feel right, so let’s change it and pass the origin as a parameter to FrontModel‘s constructor. Way better.

EObjectEvent CObject_EventSink::Recalculate()
{
	VWParametricObj object(fhObject);
	double width = object.GetParamReal(&quot;Width&quot;);
	double height = object.GetParamReal(&quot;Height&quot;);
	double depth = object.GetParamReal(&quot;Depth&quot;);
	
	SimpleCabinetModel simpleCabinetModel(width, height, depth);

	FrontModel frontModel(simpleCabinetModel.GetFrontModelOrigin());

	SimpleCabinetCreator creator(object);
	creator.CreateFrom(simpleCabinetModel, frontModel);
	
	return kObjectEventNoErr;
}

Where does SimpleCabinetCreator get the front symbols name from? FrontModel, of course. We hard-wire the name of the symbol for now:

class SimpleCabinetCreator {
	
public:
	
	SimpleCabinetCreator(const VWParametricObj& pio) : fSimpleCabinet(pio) {
	}
	
	void CreateFrom(const SimpleCabinetModel& cabinetModel, const FrontModel& frontModel) {
		
		CreateFrom(cabinetModel);
		CreateFrom(frontModel);
	}
	
private:
	
	void CreateFrom(const SimpleCabinetModel& cabinetModel) {
		// ...		
	}
	
	void CreateFrom(const FrontModel& frontModel) {
				
		MCObjectHandle firstFrontSegment = gSDK->PlaceSymbolByNameN(frontModel.GetFrontSymbolName(), frontModel.GetOrigin());
		fSimpleCabinet.AddObject(firstFrontSegment);
		
		MCObjectHandle secondFrontSegment = gSDK->PlaceSymbolByNameN(frontModel.GetFrontSymbolName(), frontModel.GetPositionOfSecondSegment());
		fSimpleCabinet.AddObject(secondFrontSegment);
	}
	
	VWParametricObj fSimpleCabinet;
	
};

Firing up Vectorworks 2011, we are supposed to be – once again – pleased with the results. However, a closer inspection reveals that the front tiles collide with the bottom board – ah, we forgot the tiles z position in our model.

Episode 5

Tune in next week when you heard Dr. Bob say: “Nurse Piggy, would you mind slapping this developer here with a rolled-up newspaper?”

Previous Episode | Next Episode


19
Apr 11

Developing a Vectorworks 2011 Plug-in, TDD-style – Episode 4

In Episode 3 – Not doing the same sketch twice, we made some good progress on a class finally capable of describing the geometry of the cabinet’s parts. In this episode, we will create Vectorworks geometry. It seems like a good idea to separate the creation of the geometry from the actual model (much in the way a View is separated from a Model in MVC). Let’s call the new SimpleCabinetCreator:

class SimpleCabinetCreator {
	
public:
	
	static void CreateFrom(const SimpleCabinetModel&amp;amp;amp;amp;amp; model) {
		
		MCObjectHandle leftSide = gSDK->CreateExtrude(0, model.GetHeight());
		gSDK->AddObjectToContainer(gSDK->CreateRectangle(model.GetLeftSideBase()), leftSide);
		
		MCObjectHandle rightSide = gSDK->CreateExtrude(0, model.GetHeight());
		gSDK->AddObjectToContainer(gSDK->CreateRectangle(model.GetRightSideBase()), rightSide);
		
		MCObjectHandle top = gSDK->CreateExtrude(model.GetTopZPosition(), model.GetTopZPosition() + model.kBoardThickness);
		gSDK->AddObjectToContainer(gSDK->CreateRectangle(model.GetTopBottomBase()), top);
		
		MCObjectHandle bottom = gSDK->CreateExtrude(0, model.kBoardThickness);
		gSDK->AddObjectToContainer(gSDK->CreateRectangle(model.GetTopBottomBase()), bottom);
		
	}
	
};

Looks good so far. The main takeaway point is that the Creator class shouldn’t do any calculation. It should be translating the model straight into Vectorworks geometry without any logic on it’s own.

While we’re at it: How about renaming SimpleCabinet to SimpleCabinetModel? This would be a nice symmetrical way of naming the classes: SimpleCabinetModel and SimpleCabinetModel. Let’s do that.

Now for the grand finale of this episode. The plug-in object’s Recalculate() method is pretty straightforward. All the basic building blocks are already in place:

EObjectEvent CObject_EventSink::Recalculate()
{
	VWParametricObj object(fhObject);
	double width = object.GetParamReal("Width");
	double height = object.GetParamReal("Height");
	double depth = object.GetParamReal("Depth");
	
	SimpleCabinetModel simpleCabinetModel(width, height, depth);
	SimpleCabinetCreator::CreateFrom(simpleCabinetModel);
	
	return kObjectEventNoErr;
}

We get the width, height & depth from the parametric object, create a model and ask the SimpleCabinetCreator to create the geometry defined in the model. Let’s fire up Vectorworks and see if everything is working as expected. And – much to our surprise – it’s working out as expected:

Episode4

Sounds like a great way to end this episode. Let’s see if we can add the front tiles in the upcoming episodes. TDD-style, of course.

Make sure to tune in next week when you hear Dr. Bob say: “A third class? I’m a quack, not a CS major.”.

Previous Episode | Next Episode