What's (currently) your favourite snippet of code?

Posted By: the_clown

What's (currently) your favourite snippet of code? - 08/12/14 19:17

Given that Acknex is often called an engine for programmers, I guess a lot of you here actually are programmers, so quick and dirty, what's currently your favourite snippet of code that does something cool with only a few lines? May be any language, any context, as long as the length/effect ratio is cool in any way.

Oh and if you feel like it, do NOT tell us what it actually does, instead let us have a guess. If it's not too hard. wink

I'll start off with my current favourite in C++ - this should be rather easy to guess:

Code:
template <class T>
static T& Instance(){
   static T t;
   return t;
}

Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/12/14 19:23

Singleton. Breaks horribly when part of a library and is used in an compilation unit that generates code linked into another binary/library. Source: Raynes singleton system breaking horribly on Windows.

My favourite. Should be easy to guess, but can someone point out the beauty of this snippet?
Code:
_titleLabel->SetFrame([&]() -> RN::Rect {
	RN::Rect rect = _titleLabel->GetFrame();
	
	rect.x = 5.0f;
	rect.y = 5.0f;
	
	return rect;
}());

Posted By: sivan

Re: What's (currently) your favourite snippet of code? - 08/12/14 19:39

probably my 1st program in Basic for C64. totally useless, sorry grin
Code:
10 PRINT "A"
20 GOTO 10

Posted By: the_clown

Re: What's (currently) your favourite snippet of code? - 08/12/14 19:43

Originally Posted By: WretchedSid
Singleton. Breaks horribly when part of a library and is used in an compilation unit that generates code linked into another binary/library. Source: Raynes singleton system breaking horribly on Windows.


Oh it does? Good to know, how exactly does it break?

Your snippet sets the size of a label, or the label's frame, to 5x5 I guess, by basically making a copy of the existing frame, modifying the properties of that copy and then setting it as new frame for the label?
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/12/14 20:18

Originally Posted By: the_clown
Oh it does? Good to know, how exactly does it break?


Assuming you have a library and a normal application, and both use this to create a singleton of type "Foo". The library and application will then both have their very own instance that is not shared. Normally the linker is responsible for getting rid of the multiple template instantiations and to make them into one, however, the linker doesn't work cross libraries, so the application and library both have their very own instances of the code and there of "Foo".

Originally Posted By: the_clown
Your snippet sets the size of a label, or the label's frame, to 5x5 I guess, by basically making a copy of the existing frame, modifying the properties of that copy and then setting it as new frame for the label?

Well, kind of. It only sets the origin and doesn't touch the size, but that's not the beauty of the snippet. Want to take another guess or should I say it?
Posted By: the_clown

Re: What's (currently) your favourite snippet of code? - 08/12/14 20:33

Ah, so the problem here is the fact that it's a templated method?
Interesting pitfall.

Hmm I could imagine it's the fact you're doing the whole thing with a single function call using C++'s Lambda feature? At least I think that's quite a nice thing.
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/12/14 20:42

Originally Posted By: the_clown
Ah, so the problem here is the fact that it's a templated method?
Interesting pitfall.

Kind of, but it wouldn't work without templates either. If you declare it static, you would get an instantiation per compilation unit that makes use of it. Without static, your linker would complain about duplicated symbols. Because it's a template, the linker will collapse the multiple instantiations down to one.

Originally Posted By: the_clown
Hmm I could imagine it's the fact you're doing the whole thing with a single function call using C++'s Lambda feature? At least I think that's quite a nice thing.

Getting close. The real nice thing is that it doesn't pollute the outer scope with "rect" and makes the whole thing look nicer (imho anyways). Here is the context: https://github.com/uberpixel/Downpour/bl...w.cpp#L169-L175

It really is just a much nicer way of writing this:
Code:
RN::Rect rect = _titleLabel->GetFrame();

rect.x = 5.0f;
rect.y = 5.0f;

_titleLabel->SetFrame(rect);

// Why does rect have to still be visible here?!



I sue this kind of sparingly and only when it makes sense to limit the scope and visibility of variables.

Edit: Are we allowed multiple posts? I know one can only have _one_ favourite, but what about other really neat snippets?
Posted By: the_clown

Re: What's (currently) your favourite snippet of code? - 08/12/14 21:04

Originally Posted By: WretchedSid

Kind of, but it wouldn't work without templates either. If you declare it static, you would get an instantiation per compilation unit that makes use of it. Without static, your linker would complain about duplicated symbols. Because it's a template, the linker will collapse the multiple instantiations down to one.


Hmm I'm trying to make sure I get you right here (even if that collapses the thread miles into off-topic, but as it's my thread I guess I can do that), you say if I made this a non-templated method and did something like this
Code:
static Singleton& Instance(){
       static Singleton s;
       return s;
}



that would break when used in a library, too?

EDIT: And you're welcome to post more than one snippet.
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/12/14 22:07

Originally Posted By: the_clown
that would break when used in a library, too?

It would just break. Static functions are only visible to the current compilation unit and aren't shared. You can test this yourself by returning the pointer to the static variable and printing that in the callee, then do this from two compilation units and link it all together.

Here is my second snippet. It also uses static variables, and it's a tad longer.
Code:
class Initializer
{
public:
	typedef void (*Callback)();
	
	Initializer(Callback ctor, Callback dtor) :
		_dtor(dtor)
	{
		if(ctor) ctor();
	}
	
	~Initializer()
	{
		if(_dtor) _dtor();
	}
	
private:
	Callback _dtor;
};

#define RN_REGISTER_INITIALIZER(name, body) \
	namespace { \
		static void __RNGlobalInit##name##Callback() { body; } \
		static RN::Initializer __RNGlobalInit##name (__RNGlobalInit##name##Callback, nullptr); \
	}
#define RN_REGISTER_DESTRUCTOR(name, body) \
	namespace { \
		static void __RNGlobalDestructor##name##Callback() { body; } \
		static RN::Initializer __RNGlobalDestructor##name (nullptr, __RNGlobalDestructor##name##Callback); \
	}

Posted By: Superku

Re: What's (currently) your favourite snippet of code? - 08/12/14 22:27

Code:
my.pan = your.pan + random(360);

Posted By: Hummel

Re: What's (currently) your favourite snippet of code? - 08/13/14 03:28

Code:
titleLabel.Frame = new Rect(5f, 5f);// C# style

Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/13/14 06:56

I feel like this is missing the width and height, no? It's not like you can't just assign things in C++ (you could actually do it by value :p), but according to the specs, the C# rect also has an origin and a size. Where's the size in your example coming from?
Posted By: Hummel

Re: What's (currently) your favourite snippet of code? - 08/13/14 15:33

dunno. getter/setter magic? there is a C#-rect?
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/13/14 17:06

So basically you are saying that you pulled that snippet out of your ass without understanding what mine does?
It's not too hard to write a really cool snippet with LINQ that actually demonstrates some cool C# stuff. Just saying.

Come on, some one impress me with C#s expression engine and the lazy evaluation of it. Go!
Posted By: Hummel

Re: What's (currently) your favourite snippet of code? - 08/13/14 17:11

The pro has spoken. Srsly...
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/13/14 17:41

Not this again...
Posted By: Michael_Schwarz

Re: What's (currently) your favourite snippet of code? - 08/13/14 17:52

Back on topic, I am sure this could have been done much, MUCH better. But since I am really terrible at maths, this is how I avoided loops for calculating the "index" (i.e. the n'th time it happened) of a weekly recurring appointment for a calendar app in javascript:

Code:
// Does it occur on target date?
if ((this.pattern.weekdays & p.date.get.dotw(h.target)))
{
    // How many week has it been since this appointment started?
    var weeksSinceStart = p.date.get.weeksBetween(h.current, h.target);

    // Skip this week?
    if (weeksSinceStart % this.pattern.periodicity)
    {
        return null;
    }

    // How many blind occurrences are there?
    // e.g. appointment starts on a WED but the pattern is MO/_WED_/TH/SU = 1 blind (MO)
    var blind_occurrences = 0;

    // Avoid loop with clever switch
    switch ((this.pattern.weekdays & p.date.get.dotw(this.start)))
    {
        // INTENTIONAL FALL-THROUGHS!!! //                                                                                                                    
        case FLAG_SUNDAY:
            (this.pattern.weekdays & FLAG_SATURDAY) && blind_occurrences++;
        case FLAG_SATURDAY:
            (this.pattern.weekdays & FLAG_FRIDAY) && blind_occurrences++;
        case FLAG_FRIDAY:
            (this.pattern.weekdays & FLAG_THURSDAY) && blind_occurrences++;
        case FLAG_THURSDAY:
            (this.pattern.weekdays & FLAG_WEDNESDAY) && blind_occurrences++;
        case FLAG_WEDNESDAY:
            (this.pattern.weekdays & FLAG_TUESDAY) && blind_occurrences++;
        case FLAG_TUESDAY:
            (this.pattern.weekdays & FLAG_MONDAY) && blind_occurrences++;
    }

    // How often has it already occurred *this* week?
    var occurrenceIndexThisWeek = -blind_occurrences;

    // Avoid loop with clever switch
    switch ((this.pattern.weekdays & p.date.get.dotw(h.target)))
    {
        // INTENTIONAL FALL-THROUGHS!!! //                                                                                                                     
        case FLAG_SUNDAY:
            (this.pattern.weekdays & FLAG_SATURDAY) && occurrenceIndexThisWeek++;
        case FLAG_SATURDAY:
            (this.pattern.weekdays & FLAG_FRIDAY) && occurrenceIndexThisWeek++;
        case FLAG_FRIDAY:
            (this.pattern.weekdays & FLAG_THURSDAY) && occurrenceIndexThisWeek++;
        case FLAG_THURSDAY:
            (this.pattern.weekdays & FLAG_WEDNESDAY) && occurrenceIndexThisWeek++;
        case FLAG_WEDNESDAY:
            (this.pattern.weekdays & FLAG_TUESDAY) && occurrenceIndexThisWeek++;
        case FLAG_TUESDAY:
            (this.pattern.weekdays & FLAG_MONDAY) && occurrenceIndexThisWeek++;
    }

    // Set index
    var index = (weeksSinceStart * this.occurrencesPerWeek / this.pattern.periodicity) + occurrenceIndexThisWeek;

Posted By: fogman

Re: What's (currently) your favourite snippet of code? - 08/13/14 17:59

using System.Collections.Generic;
Posted By: the_clown

Re: What's (currently) your favourite snippet of code? - 08/13/14 18:20

@Sid, am I right to assume that the problem with statics only occurs with the use of shared libraries, but not with the use of static libraries?
Also, I have no clue what your second snippet does. tongue

@Michael, I think I see what you did there, nice workaround.
@fog, that's not a snippet. tongue
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/13/14 21:29

Originally Posted By: the_clown
@Sid, am I right to assume that the problem with statics only occurs with the use of shared libraries, but not with the use of static libraries?

Yes.

Originally Posted By: the_clown
Also, I have no clue what your second snippet does. tongue

It provides a way to execute some code at startup or exit. The macros wrap a static object that is instantiated at startup (or when the library is loaded), and which is destroyed at the end, and depending on which macro is used, it calls a callback in either the constructor or destructor. It exploits the automatic object lifetime in C++.

Similar, a scope guard, which can be used for automatic clean up (more code snippet):
Code:
namespace RN
{
	class ScopeGuard
	{
	public:
		template<typename F>
		explicit ScopeGuard(F &&rollback) :
			_committed(false),
			_rollback(std::move(rollback))
		{}
		
		ScopeGuard(ScopeGuard &&other) :
			_committed(other._committed),
			_rollback(std::move(other._rollback))
		{}
		
		ScopeGuard &operator=(ScopeGuard &&other)
		{
			_rollback = std::move(other._rollback);
			_committed = other._committed;
			
			return *this;
		}
		
		~ScopeGuard()
		{
			if(!_committed)
				_rollback();
		}
		
		
		void Commit()
		{
			_committed = true;
		}
		
	private:
		bool _committed;
		Function _rollback;
	};
}




Example usage:
Code:
void foo()
{
	FILE *file = fopen(...);

	RN::ScopeGuard guard([&]() {
		fclose(file); // Close the file descriptor
	});

	bar(file); // In this case, bar can throw an exception. 
	// Either way, exception or normal exit, once the scope guard goes out of scope, the file is closed.
}



PS: Don't use "FILE" in C++ tongue
Posted By: MasterQ32

Re: What's (currently) your favourite snippet of code? - 08/14/14 20:06

Originally Posted By: fogman
using System.Collections.Generic;

Someone just encountered the awesomeness of having a awesome standard library?

I have two snippets:

C#
Code:
list.RemoveAll((client) => !client.Update());



C/C++
Code:
void magicFunc(char *d, const char *s) {
    while(*d++ = *s++);
}

Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/14/14 22:25

String copy and functional programming.

I can +1 the functional programming with reactive functional programming. I know that C# can do it better, but oh well.

Code:
RAC(createButton, enabled) = [RACSignal 
    combineLatest:@[ RACObserve(self, password), RACObserve(self, passwordConfirmation) ] 
    reduce:^(NSString *password, NSString *passwordConfirm) {
        return @([passwordConfirm isEqualToString:password]);
    }];

Posted By: HeelX

Re: What's (currently) your favourite snippet of code? - 08/14/14 22:26

Java 7 allows switches on strings. O-m-f-g!

Code:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {

    String typeOfDay;
    
    switch (dayOfWeekArg) {
    
        case "Monday":      typeOfDay = "Start of work week";
                            break;
    
        case "Tuesday":
        case "Wednesday":
        case "Thursday":    typeOfDay = "Midweek";
                            break;
    
        case "Friday":      typeOfDay = "End of work week";
                            break;
    
        case "Saturday":
        case "Sunday":      typeOfDay = "Weekend";
                            break;
    
        default:            throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
    }
    
    return typeOfDay;
}

Posted By: Zapan@work

Re: What's (currently) your favourite snippet of code? - 08/14/14 22:45

Code:
float Q_rsqrt( float number )
{
	long i;
	float x2, y;
	const float threehalfs = 1.5F;
 
	x2 = number * 0.5F;
	y  = number;
	i  = * ( long * ) &y;                       // evil floating point bit level hacking
	i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
	y  = * ( float * ) &i;
	y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed
 
	return y;
}

Posted By: MasterQ32

Re: What's (currently) your favourite snippet of code? - 08/14/14 22:50

@Sid: I just wondered that you know C# that good, but then i stopped wondering. Testing programming languages is a nice thing, but sometimes hard to get into
I for myself keep distance to Objective-C, so much parenthesis, @s and stuff tongue

@HeelX: And that's why C# is better. Could do it from day 0. tongue
No, just kidding, but i have a strong personal preference to C# over Java as i like the concepts built into the language (structs, function pointers / delegates and the standard library is really awesome)

Another snippet in Lua:
Code:
Object = { new = function (self)
  local o = {}
  setmetatable(o, self)
  self.__index = self
  return o
end }



EDIT: @Zapan@work:
One of the most awesome C hacks i've ever seen.
Posted By: Michael_Schwarz

Re: What's (currently) your favourite snippet of code? - 08/15/14 07:24

Originally Posted By: MasterQ32
i have a strong personal preference to C# over Java


fuck java, seriously. Fuck it right up the fucking arse with a 100" big black dildo.

edit: a dildo with titanium thorns and coated in 1.000.000 scoville hot sauce. On fire.
Posted By: MasterQ32

Re: What's (currently) your favourite snippet of code? - 08/15/14 08:01

+1
Posted By: HeelX

Re: What's (currently) your favourite snippet of code? - 08/15/14 17:08

Originally Posted By: Michael_Schwarz
Originally Posted By: MasterQ32
i have a strong personal preference to C# over Java


fuck java, seriously. Fuck it right up the fucking arse with a 100" big black dildo.

edit: a dildo with titanium thorns and coated in 1.000.000 scoville hot sauce. On fire.
Can this scale up? And sideways? Nope? Meh.
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 08/15/14 17:36

That dildo can scale diagonally if you use it with the wrong angle
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 08/15/14 19:19

my.pan = your.pan + random(360);
Posted By: MasterQ32

Re: What's (currently) your favourite snippet of code? - 08/16/14 21:18

Code:
"".GetType()

Posted By: Redeemer

Re: What's (currently) your favourite snippet of code? - 08/17/14 18:57

Code:
for( v=0; v<TEXTURESIZE; v++ ) {
	SDL_GetRGB(getPixel(texture,u,v),screen->format,&b,&g,&r);
	color = SDL_MapRGB(screen->format,r,g,b);
	while( texelcount<=max(1.0,texelsize) && y<camera->winy+camera->winh ) {
		if( y>=camera->winy ) {
			*(Uint32 *)((Uint8 *)p + scanline)=color; // draw pixel
			scanline += scanwidth;
		}
		y++;
		texelcount+=min(texelsize,1.0);
	}
	texelcount -= max(1.0,texelsize);
	if( y>=camera->winh+camera->winy )
		break;
}


Column-based texture mapping on a per texel basis. It seems obvious but I just realized it a year ago, and it massively improved the speed of my raycaster when the camera was positioned close to walls. UV coordinates are recalculated only when the end of the texel is reached (instead of for every pixel), and if texelsize<0 the more obvious per-pixel method is used instead.

Also:
Code:
fld fnum
fistp inum


Fast float to integer conversion in x86. Weirdly enough I've found that many compilers will not do this. I discovered the trick several years ago and then found sometime later that John Carmack did the same thing in Quake 2.

Originally Posted By: Superku
Code:
my.pan = your.pan + random(360);


Where did you find this? grin
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 08/17/14 19:28

Devil City.
Posted By: Redeemer

Re: What's (currently) your favourite snippet of code? - 08/17/14 20:33

Originally Posted By: Firoball
Devil City.

Ich verstehe ganz nicht, ist das irgendeine Art von Spiel?
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 08/17/14 20:36

http://www.conitec.net/images/a4links.htm

Site is offline, though.
Posted By: Superku

Re: What's (currently) your favourite snippet of code? - 08/17/14 20:51

Devil City was THE game back then in the old forum days, with 80-120 enemy types, a cool blocky outdoor level covered in fog and a mediocre sewer level. Sadly and not surprisingly it was mostly a hoax, and "Devil" was not the coder he promised to be.
Posted By: ventilator

Re: What's (currently) your favourite snippet of code? - 08/17/14 21:25

was he the guy who left the forum by making a last post where he regretted that he wasted his whole youth with gamestudio (instead of chasing girls)? oh... all the drama this forum has seen... laugh
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 08/18/14 16:13

Originally Posted By: ventilator
was he the guy who left the forum by making a last post where he regretted that he wasted his whole youth with gamestudio (instead of chasing girls)? oh... all the drama this forum has seen... laugh


yeth.
And I think he called me some sort of nazi or the like tongue
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 08/19/14 19:51

Code:
#include <acknex.h>
#include <windows.h>

typedef int HKEY;
typedef int REGSAM;

long WINAPI RegEnumKeyEx(
	HKEY hKey,
	DWORD dwIndex,
	char *lpName, 
	long *lpcName,
	long *lpReserved, 
	char *lpClass, 
	long *lpcClass, 
	FILETIME *lpftLastWriteTime);
	
long WINAPI RegOpenKeyEx(HKEY hKey, char *lpSubKey, DWORD ulOptions, REGSAM samDesired, HKEY *phkResult);

long WINAPI RegCloseKey(HKEY hKey);

function main()
{
	HKEY hTestKey;
	if(RegOpenKeyEx(HKEY_CURRENT_USER,
		"SOFTWARE\\Unity Technologies",
		0,
		KEY_READ,
		&hTestKey) == ERROR_SUCCESS )
	{
		error("Traitor!");
		RegCloseKey(hTestKey);
	}
	else
	{
		error("All fine!");
	}
   
}



Snippet taken from Prince of Lotteria. grin
Posted By: Kartoffel

Re: What's (currently) your favourite snippet of code? - 08/19/14 20:25

haha grin
Posted By: Michael_Schwarz

Re: What's (currently) your favourite snippet of code? - 08/19/14 20:31

Damn we forgot the Ackchievements in Ackmania!
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 08/19/14 20:33

We forgot on intention grin
We wanted to have more time for the actual game (honestly!).
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 10/07/14 22:54

This lock free ringbuffer implementation. Supports one reader and one writer.

Code:
template<class T, size_t Size>
class lock_free_ring_buffer
{
public:
	lock_free_ring_buffer() :
		_head(0),
		_tail(0)
	{}
	
	bool push(const T &val)
	{
		size_t tail = _tail.load(std::memory_order_relaxed);
		size_t next = (index + 1) % capacity;
		
		if(next != _head.load(std::memory_order_acquire))
		{
			_buffer[tail] = val;
			_tail.store(next, std::memory_order_release);
			
			return true;
		}
		
		return false;
	}
	
	bool pop(T &val)
	{
		size_t head = _head.load(std::memory_order_relaxed);
		
		if(head != _tail.load(std::memory_order_acquire))
		{
			val = std::move(_buffer[head]);
			_head.store((index + 1) % capacity, std::memory_order_release);
			
			return true;
		}
		
		return false;
	}
	
	bool was_empty() const
	{
		return (_head.load() == _tail.load());
	}
	
private:
	enum { capacity = Size + 1 };
	
	std::atomic<size_t> _head;
	std::atomic<size_t> _tail;
	
	std::array<T, capacity> _buffer;
};

Posted By: MasterQ32

Re: What's (currently) your favourite snippet of code? - 10/08/14 01:27

C# and some kind of unicode code:
Posted By: Redeemer

Re: What's (currently) your favourite snippet of code? - 10/08/14 04:26

Something I often take for granted as an american is how basically all programming languages worth mentioning were designed in English by default.

There was no moment for me when I learned what certain keywords really meant because for me it was always intuitive.
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 10/08/14 15:45

Not actually a snippet, but the explanation of an atrocity...

http://stackoverflow.com/questions/54137...-function-calls
Posted By: Redeemer

Re: What's (currently) your favourite snippet of code? - 10/08/14 15:50

I hate languages that do this, maintaining multiple valid approaches to key syntax is pointless and retarded and only serves to break down the usefulness of a language to describe implementations in a consistent and predictable manner.
Posted By: FBL

Re: What's (currently) your favourite snippet of code? - 10/08/14 16:57

yes.
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 04/27/15 00:02

The following reference counting implementation:

Code:
Object *Object::Retain()
{
	_refCount.fetch_add(1, std::memory_order_relaxed);
	return this;
}

void Object::Release()
{
	if(_refCount.fetch_sub(1, std::memory_order_release) == 1)
	{
		std::atomic_thread_fence(std::memory_order_acquire); // Synchronize all accesses to this object before deleting it

		CleanUp();
		delete this;
	}
}



For the longest time I did reference counting with strong memory fences (std::memory_order_acq_rel), until I learned that relaxed ordering works with read-modify-write operations just fine.
The release operation is a bit more complicated because if this is the last reference the thread holds to the object, it needs to have a full release operation. However, only the final thread that relinquishes the reference needs an acquire operation to make sure all changes to the object are observed before entering the destructor.

Clever as fuck. The basic idea comes from Herb Sutter's Atomic<> Weapons talk, although he used std::memory_order_acq_rel for dropping a reference.


Of course this doesn't do anything for strongly ordered architectures like x86, but it produces much better code on weakly ordered CPUs like ARM.
Posted By: the_clown

Re: What's (currently) your favourite snippet of code? - 04/27/15 07:26

Funny enough, the last thing I've implemented in C++ was a reference counted object class to see how that stuff is put together - without any synchronization though, thread safe code is something I still have to explore.

I have one question though (very offtopic but hey these forums are more or less anarchistic by now anyways), Sid: You have this nice Object class in Rayne, which gives you all these nifty features like reflection, reference counting, etc, but the fact that they're reference counted enforces allocation of objects on the heap - so how do you make that work nicely with cache-friendly processing of objects? I suppose you're using a custom allocator (or multiple) to ensure objects are allocated close to each other, but I still can't imagine that this is as optimal as it could be with tightly packed object buffers.
Or, to rephrase my actual question in a way so you could answer it with a yes or a no, did the comfortable features of having this base object class outweigh the possible performance gains of having a less abstracted, but more data-oriented object model for you? Or do you perform some kind of programming magic in the background so the nice API of your object model just hides an optimized implementation?

I hope my question is somewhat clear, I'm doing a lot of research regarding different object models currently and I'm basically just trying to squeeze every sponge I can get into my hands, if you will, for first hand experiences. tongue (Especially because most opinions you find on public blogs are those of very very C-affine data-orientation fanatics, which may be a fascinating and important topic, but it's not really helpful to simply be told to scrap all OOP and make everything a system stacked onto another system then feed them data, without any explanations on how to architect such a structure in a codebase that's still somewhat flexible).
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 04/27/15 12:12

It turns out that it works extremely well. Not everything inherits from Object though, only high level objects that are long lived, SceneNodes for example are objects whereas vectors (not the container kind) are not.

It does sacrifice a bit of cache locality, but brings tremendous up sides with it, so it's well worth it. Also given that many objects can form one/many-to-many relationships with each other, you would lose that cache locality anyway (parent -> child relationships of scene nodes for example).

There are many classes which don't inherit from object because they don't need to, and some go as far as being trivial classes to allow for fast copy operations.

On the other hand, we have one construct that is explicitly out to blow cache locality: The weak object table! Rayne gained smart pointer support that nicely wrap the Object class, and one of the smart pointers is a weak pointer which stores a reference to the object at runtime in the weak table. The weak table is a multi level hash table, with the top level having 8 buckets. The buckets are allocated as one large memory chunk, but each bucket is sized to be larger than a CPU cache line, so in an ideal world multiple CPUs accessing the weak table don't suffer from false sharing.
Posted By: the_clown

Re: What's (currently) your favourite snippet of code? - 05/01/15 09:18

Ah, I thought the weak table was to store the weak pointers for access from the object for bookkeeping - this way around it actually makes more sense.
One thing I'm still struggling with is the fact that everybody can just go and retain an object - what if you want to force deletion of an object? Like, for example, a SceneNode that should be removed from the scene? As far as I understand it, someone somewhere could always be storing a reference to it via a Retain() call, and would not be notified of the deletion because he's not using a weak pointer, so he's left with a dangling pointer. I wonder if there's a way to solve that, besides forcing everyone to use the weak pointer type.
Posted By: WretchedSid

Re: What's (currently) your favourite snippet of code? - 05/01/15 12:56

Actually, the scene itself should act as a container and retain the scene node. If you spawn for example a bunch of static scenery that you don't need to touch ever again, why be forced to keep a reference around and track that when the scene in reality is pretty much a container? When the scene is destroyed, it relinquishes all it references, and you don't need to track it.

There should also be ways to add and remove objects from a scene, for example, what if you have an object that is rather expensive to create so it's easier to just keep around and add it to the scene again when it's needed. An enemy for example, you shoot it dead, remove it from the scene and later put it back in when a new enemy needs to spawn. If your code requires a strong reference, then it should have it, no reason to force arbitrary limitations onto things.

There used to be a really dirty hack in Rayne that removed nodes that hit a retain count of 0 from the world, so over releasing a scene node was okay. I don't think that will make it back though.
© 2024 lite-C Forums