View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

Sign up now

# Sorted particles and SIMD

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

3 replies to this topic

### #1Juliean  Members

Posted 21 April 2013 - 09:33 AM

Hello,

mainly as a learning experience, but also to aid my further developement, I want to enchance my particle system using SIMD, as featured in this article: http://software.intel.com/en-us/articles/creating-a-particle-system-with-streaming-simd-extensions.

Now my main problem is that, unlike them, I want my particles to being sorted. This is a problem, since SIMD seems to rely on the data being accessed in a linear manner (from i to i+3), which isn't working all that well with my current approach. This is how depth updating looks currently:

	const D3DXVECTOR3& vPos(camera.GetPosition());
for(DepthVector::iterator ii = m_vDepth.begin(); ii != m_vDepth.end(); ++ii)
{
//get index of currect particle to keep temporal coherency
const unsigned int index = ii->index;
ii->depth = abs(m_particles.x[index] - vPos.x);
ii->depth += abs(m_particles.y[index] - vPos.y);
ii->depth += abs(m_particles.z[index] - vPos.z);
}

std::sort(m_vDepth.begin(), m_vDepth.end(), ParticleSorter());


As you can see, I perform an index sort, later on I'll use that index to identify the particle. Note that since I'm using an SoA I can't really sort that itself... can I? Anyway, now this is the code I've written so far in SIMD:

void ParticleEmitter::SortParticles(const D3DXVECTOR3& vCameraPos)
{
//load camera position and create depth register
__m128 cameraPosX = _mm_set1_ps(vCameraPos.x), cameraPosY = _mm_set1_ps(vCameraPos.y), cameraPosZ = _mm_set1_ps(vCameraPos.z), depthRegister;
//register for abs()-ing
__m128 dummy = _mm_set1_ps(1.0f);

__declspec(align(16)) float depth[4];

// number of 4 elements we can process
const unsigned int remainingParticles = m_vDepth.size() % 4;
//get vector iterator
DepthVector::iterator ii = m_vDepth.begin();
//
for(unsigned int i = 0; i < m_cParticles - remainingParticles; i+=4)
{
//set register to X-component of camera distance -> abs( ParticleX - CameraX )
depthRegister = _mm_andnot_ps(dummy, _mm_sub_ps( _mm_load_ps(&m_particles.x[i]), cameraPosX) );
//add Y-component -> abs( ParticleY - CameraY)
_mm_add_ps(depthRegister, _mm_andnot_ps(dummy, _mm_sub_ps( _mm_load_ps(&m_particles.y[i]), cameraPosY) ) );
//add Z-component -> abs( ParticleZ - CameraZ)
_mm_add_ps(depthRegister, _mm_andnot_ps(dummy, _mm_sub_ps( _mm_load_ps(&m_particles.z[i]), cameraPosZ) ) );

//load depth
_mm_store_ps(depth, depthRegister);

//set depth
ii->depth = depth[0];
ii++;
ii->depth = depth[1];
ii++;
ii->depth = depth[2];
ii++;
ii->depth = depth[3];
ii++;
}

std::sort(m_vDepth.begin(), m_vDepth.end(), ParticleSorter());
}


Now there are two problems with the code:

- Number one, I don't see how to keep temporal coherence, as I did before. This is very bad, as re-sorting the previous-frame sorted depth list is almost twice as fast as the unordered one. Is there any way to perform index sorting, or some other way of sorting particles that is compatible with SIMD?

- Number two, this code is only running half of the time. Sometimes it crashes on the first "ii->depth = depth[i]" - line, stating something about a read access violation at a non-null memory adress. It always crashes at another "i", so there really is no pattern, looking at the debugger doesn't tell me anything, since all values seem to be okay, and the adress the error message tells isn't anywhere I can look at in the MSVC debugger. Since I'm new to SIMD, maybe someone can see a mistake in the code I cannot see? Nevermind, shouldn't have done depth[i], depth[i+1] ... but depth[0], depth[1]... fixed the crash, but the first problem still resides - the SIMD code performs far worst er (0.0055 ms instead of 0.003 ms), and profiling tells me that all the performance I gain from quatering the work needed for depth calculation is more than lost lost because the depth vector needs to be sorted frame after frame again from scratch. Any ideas?

In case you wonder, this is how I declare the regarding structs:

struct Particles
{
#define BOUNDARY_ALIGNMENT 16

Particles(unsigned int count)
{
/*x = new float[count];
y = new float[count];
z = new float[count];*/
x  = (float*)_mm_malloc(count * sizeof(float), BOUNDARY_ALIGNMENT);
y  = (float*)_mm_malloc(count * sizeof(float), BOUNDARY_ALIGNMENT);
z  = (float*)_mm_malloc(count * sizeof(float), BOUNDARY_ALIGNMENT);
}

~Particles(void)
{
_mm_free(x);
_mm_free(y);
_mm_free(z);
/*delete[] x;
delete[] y;
delete[] z;*/
}

float* x, *y, *z;
};

struct ParticleDepth
{
int index;
float depth;
};


Thanks in advance!

Edited by Juliean, 21 April 2013 - 10:10 AM.

### #2C0lumbo  Members

Posted 21 April 2013 - 10:19 AM

You might try a radix sort instead of a std::sort.

In general a std::sort is O(n*log(n)) complexity and a radix sort is O(n), so it's often faster for large sets. A radix sort's speed will not be affected by the sortedness of the original array, so the fact you have to sort from scratch will not affect you.

Whether SIMD + Radix sort will actually end up beating your original approach which took advantage of temporal coherency to accelerate sorting is something you'd have to measure, but my gut feeling is that it's definitely worth a go.

### #3Juliean  Members

Posted 21 April 2013 - 11:15 AM

Thanks for the input,

but unfortunately the radix sort performs even worse (takes almost twice the time), but thats probably due to my bad implementation:


void acl::gfx::radixsort(ParticleEmitter::DepthVector::iterator first, ParticleEmitter::DepthVector::iterator last, int factor)
{
// partitionieren
std::map<int, std::vector<int> > buckets;
for (ParticleEmitter::DepthVector::const_iterator i = first; i != last; ++i) {
// get digit and map to bucket
if (factor == 10) buckets[i->depth%factor].push_back(i->depth);
else buckets[(i->depth/(factor/10)) %10].push_back(i->depth);
}

// collect
ParticleEmitter::DepthVector::iterator copyfirst = first;
for (int i = 0; i < 10; ++i) {
for (std::vector<int>::const_iterator it = buckets[i].begin(); it != buckets[i].end(); )
// collect and apply changes
copyfirst++->depth = *it++;
}

if (factor > std::max_element(first, last, ParticleSorter())->depth) return;
radixsort(first, last, factor *= 10);
}


Do you maybe have a better radix implementation so I could give it another shot? My struct now uses an int as key:

		struct ParticleDepth
{
int index;
int depth;
};


Edited by Juliean, 21 April 2013 - 11:16 AM.

### #4EVIL_ENT  Members

Posted 22 April 2013 - 02:26 AM

my code appears to be roughly twice as fast as std::sort for big n in my probably wrong tests:

http://ideone.com/5aBW1x

#include <stdlib.h>
#include <stdint.h>

#include <time.h>
#include <assert.h>

#include <algorithm>
#include <iostream>

void radix_sort(uint32_t *in, uint32_t *out, int shift, int n){
int index[256] = {};
for (int i=0; i<n; i++) index[(in[i]>>shift)&0xFF]++;
for (int i=0, sum=0; i<256; i++) sum += index[i], index[i] = sum - index[i];
for (int i=0; i<n; i++) out[index[(in[i]>>shift)&0xFF]++] = in[i];
}
void check(int n){
uint32_t *data = new uint32_t[n];
uint32_t *temp = new uint32_t[n];
uint32_t *same = new uint32_t[n];
for (int i=0; i<n; i++) same[i] = data[i] = (rand()<<16)|rand();// Note: rand() might not produce enough randomness

clock_t t_radix = clock();

radix_sort(data, temp,  0, n);
radix_sort(temp, data,  8, n);
radix_sort(data, temp, 16, n);
radix_sort(temp, data, 24, n);

t_radix = clock() - t_radix;

clock_t t_sort = clock();

std::sort(same, same+n);

t_sort = clock() - t_sort;

std::cout << "n: " << n << std::endl;
std::cout << "radix_sort: " << t_radix << std::endl;
std::cout << "  std:sort: " << t_sort  << std::endl;
std::cout << std::endl;

for (int i=0; i<n; i++) assert(same[i] == data[i]);

delete[] data;
delete[] temp;
delete[] same;
}

int main(){
for (int i=0; i<30; i++) check(1<<i);
return 0;
}



Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.