Jump to content

A Look at C++11 Shared Pointers in Leadwerks 5

Josh

1,564 views

C++11 introduces shared pointers, a powerful language feature that provides easy memory management without the overhead of garbage collection.  The example below should look familiar to you:

#include "Leadwerks.h"

using namespace Leadwerks;

int main(int argc, const char *argv[])
{
	shared_ptr<Leadwerks::Window> window = Leadwerks::Window::Create();

	shared_ptr<Context> context = Context::Create(window);

	shared_ptr<World> world = World::Create();

	shared_ptr<Camera> camera = Camera::Create();
	camera->SetRotation(35, 0, 0);
	camera->Move(0, 0, -6);

	shared_ptr<Light> light = DirectionalLight::Create();
	light->SetRotation(35, 35, 0);

	shared_ptr<Model> model = Model::Box();
	model->SetColor(1.0, 0.0, 0.0);
	model->SetPosition(-4, 0, 0);

	while (true)
	{
		if (window->Closed() || window->KeyDown(Key::Escape)) return false;
		
		Leadwerks::Time::Update();
		world->Update();
		world->Render();
		context->Sync();
	}
  
	//Everything will get automatically deleted when we return from this function
	return 0;
}

Using the auto keyword simplifies everything (and it makes this code compatible with Leadwerks 4):

#include "Leadwerks.h"

using namespace Leadwerks;

int main(int argc, const char *argv[])
{
	auto window = Leadwerks::Window::Create();

	auto context = Context::Create(window);

	auto world = World::Create();

	auto camera = Camera::Create();
	camera->SetRotation(35, 0, 0);
	camera->Move(0, 0, -6);

	auto light = DirectionalLight::Create();
	light->SetRotation(35, 35, 0);

	auto model = Model::Box();
	model->SetColor(1.0, 0.0, 0.0);
	model->SetPosition(-4, 0, 0);
	
	while (true)
	{
		if (window->Closed() || window->KeyDown(Key::Escape)) return false;
		
		Leadwerks::Time::Update();
		world->Update();
		world->Render();
		context->Sync();
	}
  
  	//Everything will get automatically deleted when we return from this function
	return 0;
}

Now things get interesting.  This function would normally cause a horrible memory leak, but with shared pointers everything is fine:

void SaveTexture(shared_ptr<Texture> tex)
{
	auto bank = Bank::Create(tex->GetMipmapSize());
	tex->GetPixels(bank->buf);
	bank->Save("pixeldata.dat");
}

Yet shared pointers can still equal nullptr:

auto bank = Bank::Create();
bank.reset();
Debug::Assert(bank==nullptr);

You can even simply set a shared pointer to nullptr, and if that was the last pointer that referenced it, it gets deleted!

auto bank = Bank::Create();
bank = nullptr;// auto deletion here!

How to Delete an Entity
The code below will not delete the entity, because a shared pointer is still stored in the world.

auto entity = Pivot::Create();
entity = nullptr;

The entity must be have its world set to NULL, and the shared pointer must be set to NULL or go out of scope:

entity = Pivot::Create();
entity->SetWorld(nullptr);
entity = nullptr;

Children use a weak pointer to the parent, so they will not cause self-referencing.

Asset Management
You no longer have to worry about calling Release() when loading assets:

auto material = Material::Create();
auto texture = Texture::Load("mytex.tex");
material->SetTexture(texture);
texture = nullptr;

Unused assets will automatically be deleted if they go out of scope:

auto material = Material::Create();
auto texture = Texture::Load("mytex.tex");
material->SetTexture(texture);
texture = nullptr;
material = nullptr;

But if they are in use, they will be retained in memory:

auto material = Material::Create();
auto texture = Texture::Load("mytex.tex");
material->SetTexture(texture);
model->SetMaterial(material);
texture = nullptr;
material = nullptr;

In conclusion, shared pointers automate many of the tasks we have been doing manually with the Leadwerks reference counting system and the AddRef and Release commands.



4 Comments


Recommended Comments

This feature is going to make the Leadwerks 5 editor a lot easier to write.

Share this comment


Link to comment

I take it the above code examples means you've already started transitioning LE to shared pointers?

What happens if you call delete on a shared pointer? Will I also have to transition my code when migrating to LE 5.5?

Share this comment


Link to comment
13 minutes ago, martyj said:

I take it the above code examples means you've already started transitioning LE to shared pointers?

I am adding defines in the code so the Leadwerks 4 source can be compiled in both modes.  It's nowhere near functional, I just started experimenting with it.  The LEADWERKS_5 define will keep the v5 stuff from messing with the current version.

13 minutes ago, martyj said:

What happens if you call delete on a shared pointer? Will I also have to transition my code when migrating to LE 5.5?

They did a nice job with the implementation of this.  It looks like delete will just call the reset() function:
https://stackoverflow.com/questions/12321949/explicitly-deleting-a-shared-ptr

That means if this is the only handle to the object, the object will be deleted.  Otherwise, the shared pointer will just have its ref count decremented.  (In Leadwerks 4 you should be calling Release() on Leadwerks objects, not delete.)

Note that the Release() and AddRef() functions will not exist in Leadwerks 5.

Share this comment


Link to comment
23 minutes ago, jen said:

This is optional right? We can still use the traditional method of assigning a type for each variable in our projects? 

I prefer the traditional way to be honest. Especially when developing multiplayer.

The type is a shared pointer (instead of a pointer).  The first example above shows how it is done.  I prefer the auto keyword because it is less to type.

Share this comment


Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Blog Entries

    • By Josh in Josh's Dev Blog 0
      A new update is available for beta testers.
      Terrain
      The terrain building API is now available and you can begin working with it, This allows you to construct and modify terrains in pure code. Terrain supports up to 256 materials, each with its own albedo, normal, and displacement maps. Collision and raycasting are currently not supported.
      Fast C++ Builds
      Precompiled headers have been integrated into the example project. The Debug build will compile in about 20 seconds the first run, and compile in just 2-3 seconds thereafter. An example class is included which shows how to add files to your game project for optimum compile times. Even if you edit one of your header files, your game will still compile in just a few seconds in debug mode! Integrating precompiled headers into the engine actually brought the size of the static libraries down significantly, so the download is only about 350 MB now.
      Enums Everywhere
      Integer arguments have been replaced with enum values for window styles, entity bounds, and load flags. This is nice because the C++ compiler has some error checking so you don't do something like this:
      LoadTexture("grass.dds", WINDOW_FULLSCREEN); Operators have been added to allow combining enum values as bitwise flags.
      A new LOAD_DUMP_INFO LoadFlags value has been added which will print out information about loaded files (I need this to debug the GLTF loader!).
      Early Spring Cleaning
      Almost all the pre-processor macros have been removed from the Visual Studio project, with just a couple ones left. Overall the headers and project structure have been massively cleaned up.
    • By Josh in Josh's Dev Blog 6
      An often-requested feature for terrain building commands in Leadwerks 5 is being implemented. Here is my script to create a terrain. This creates a 256 x 256 terrain with one terrain point every meter, and a maximum height of +/- 50 meters:
      --Create terrain local terrain = CreateTerrain(world,256,256) terrain:SetScale(256,100,256) Here is what it looks like:

      A single material layer is then added to the terrain.
      --Add a material layer local mtl = LoadMaterial("Materials/Dirt/dirt01.mat") local layerID = terrain:AddLayer(mtl) We don't have to do anything else to make the material appear because by default the entire terrain is set to use the first layer, if a material is available there:

      Next we will raise a few terrain points.
      --Modify terrain height for x=-5,5 do for y=-5,5 do h = (1 - (math.sqrt(x*x + y*y)) / 5) * 20 terrain:SetElevation(127 + x, 127 + y, h) end end And then we will update the normals for that whole section, all at once. Notice that we specify a larger grid for the normals update, because the terrain points next to the ones we modified will have their normals affected by the change in height of the neighboring pixel.
      --Update normals of modified and neighboring points terrain:UpdateNormals(127 - 6, 127 - 6, 13, 13) Now we have a small hill.

      Next let's add another layer and apply it to terrain points that are on the side of the hill we just created:
      --Add another layer mtl = LoadMaterial("Materials/Rough-rockface1.json") rockLayerID = terrain:AddLayer(mtl) --Apply layer to sides of hill for x=-5,5 do for y=-5,5 do slope = terrain:GetSlope(127 + x, 127 + y) alpha = math.min(slope / 15, 1.0) terrain:SetMaterial(rockLayerID, 127 + x, 127 + y, alpha) end end We could improve the appearance by giving it a more gradual change in the rock layer alpha, but it's okay for now.

      This gives you an idea of the basic terrain building API in Leadwerks 5, and it will serve as the foundation for more advanced terrain features. This will be included in the next beta.
    • By Josh in Josh's Dev Blog 1
      Here are some things I did in the last couple days to fix a computer that was basically unusable.
      It seems that Superfetch was rebranded to "SysMain" in an update and automatically re-enabled. If your computer is grinding away either the CPU or disk usage while doing nothing, this is the culprit. Disable it in Windows services.
      The XBox games bar is suspect. I recommend disabling it now that FRAPS supports Vulkan.
      Some features in Visual Studio are making it unusably slow.
      In Project settings > Link > Debugging, set "Generate Debug Info" to "DEBUG:FASTLINK" (in the debug build only) for faster linking.
      Disable these two settings in the general program Options:
      Enable Diagnostic Tools while debugging Show elapsed time PerfTip while debugging
×
×
  • Create New...