How do i fix my spatial hashing algorithm

36 views Asked by At

I want to create an easy way to look up particles in my fluid system using a grid search method I have found but it doesn't seem to work properly.

Can someone look at my class and see what I may have done wrong this is the class? The query function should return the nearby particles, but I keep getting errors saying:

script.js:293 Uncaught TypeError: this.grid[index] is not iterable
    at HashTable.query (script.js:293:39)
    at Particle.updateAcceleration (script.js:96:39)
    at Particle.simulateParticle (script.js:192:14)
    at physics (script.js:331:16)
    at simulate (script.js:375:5)

and the particles don't seem to be working properly. These errors occurred after adding this class:

class HashTable{
    constructor(){
        this.spacing = 2*smoothinglength;
        this.numX = Math.floor(simWidth/this.spacing);
        this.numY = Math.floor(simHeight/this.spacing);
        this.tableSize = this.numX*this.numY;
        this.grid = new Array(this.tableSize+1).fill([]);  
    }
    updateTable() {
       this.grid = new Array(this.tableSize+1).fill([]);  
       for (let i = 0; i < numParticles; i++) {
           let particle = fluidSimulator.particles[i];
           particle.xi = Math.floor(particle.position.x / this.spacing);
           particle.yi = Math.floor(particle.position.y / this.spacing);
  

           let index = particle.xi * this.numY + particle.yi;
           particle.index = index;
           // Initialize the array at the calculated index if it's undefined
           if (!this.grid[particle.index ]) {
               this.grid[particle.index ] = [];
           }
  
           this.grid[particle.index].push(particle);
     }
   }
   query(xi,yi){
       const nearbyParticles = [];
       const nearbyParticlesref = [];

       for (let dx = -1; dx <= 1; dx++) {
           for (let dy = -1; dy <= 1; dy++) {
               const newX =xi + dx;
               const newY = yi + dy;

               // Check if the new coordinates are within the valid range

               const index = newX * this.numY + newY;  
               if (newX >=0 && newX <= this.numX && newY >=0 && newY <= this.numY){
                   nearbyParticlesref.push(index)

               }

            
         }
     }
    for (const index of nearbyParticlesref){
        for( const particle of this.grid[index]){
            nearbyParticles.push(particle)
         }
    }

    return nearbyParticles
}  
0

There are 0 answers