www.xbdev.net
xbdev - software development
Friday February 6, 2026
Home | Contact | Support | WebGPU Graphics and Compute ... | Neural Networks and WebGPU Compute.. Learning from Data.....
     
 

Neural Networks and WebGPU Compute..

Learning from Data.....

 


Collision Detection (2D Spheres)


Teaching neural network to detect the collision (intersection of two objects).

• Neural network (6,12,12,1) - obj1(x,y) and radius (r1), obj2(x,y) and radius (r2)


Output for the collision detection neural network example (checks intersection of two sphere - one sphere is able to be moved a...
Output for the collision detection neural network example (checks intersection of two sphere - one sphere is able to be moved around using the mouse cursor.)




Complete Code


// Collision Detection Objects (Using Neural Network)
await xinitialize( {layers:[6,12,12,1], build:'cpu'learningrate:0.2} );

let div document.createElement('div');
document.body.appendChilddiv );
div.innerHTML = `
<h1 align='center'>Collision Detection - Learning Neural Network</h1>
<br><br>
<canvas id="mycanvas" width="512" height="512" style="border:1px solid #ff0000;"> </canvas>
<br><br>
<div id="counter">Iteration:</div>
<br>
<div id="result">Collision:</div>
`;

var 
canvas      null;
var 
context     null;
var 
iteration   0;    
var 
mousePos    = [ 100100 ];
var 
col         "blue";
var 
testSphere = [ [200,100], 40 ]; // pos,radius
    
document.onmousemove handleMouseMove;
function 
handleMouseMove(event) {
    
event event || window.event// IE-ism
    
    
canvas    canvas || document.getElementById('mycanvas');
    
context   context || canvas.getContext('2d');
    var 
rect canvas.getBoundingClientRect();
    
    
mousePos  = [event.clientX rect.leftevent.clientY rect.top];
}

function 
drawCircleposrcol )
{
    
canvas    canvas || document.getElementById('mycanvas');
    
context   context || canvas.getContext('2d');
        
    
context.fillStyle "#000ff0";
    
// arc(x, y, radius, startAngle, endAngle, anticlockwise)
    
context.strokeStyle col;
    
context.beginPath();
    
context.arc(pos[0]-r*0.5pos[1]-r*0.5r0Math.PI 2true); 
    
context.stroke(); // Draws the Circle. 
}


function 
checkCollisionposAradAposBradB )
{
    
let dist =  Math.sqrtMath.powposA[0]-posB[0],) + Math.powposA[1]-posB[1],) );
    
    if ( 
dist < (radA radB) )
    {
        return 
1;
    }
    return 
0;
}

async function preview(){
    
// check if data/images is still loading
    
if ( mousePos.length )
    {
        
requestAnimationFrame(preview);
        return;
    }
    
iteration++;
    
    var 
elem document.getElementById('counter');
    
elem.innerHTML "Iteration: " iteration;
        
    
canvas    canvas || document.getElementById('mycanvas');
    
context   context || canvas.getContext('2d');
        
    
context.clearRect(00context.canvas.widthcontext.canvas.height);

    
drawCirclemousePos20col );
    
drawCircletestSphere[0], testSphere[1], col );
    

  
    var 
datain = [ mousePos[0],    mousePos[1], 
                   
20,
                   
testSphere[0][0],   testSphere[0][1],
                   
testSphere[1] ];
            
    for (var 
i=0i<datain.lengthi++)
    {
        
datain[i] = datain[i]/512;
    }
    var 
dataout await xactivatedatain ); 
    
    
elem document.getElementById('result');
    
elem.innerHTML "Collision: " dataout[0];
    
    
// draw the shapes in red if your network says their is a collision
    
if ( dataout[0] > 0.5 )
    {
        
col "red";
    }
    else 
    {
        
col "blue";
    }
    
    
// check our 'checkCollision' function works
    /*
    if ( checkCollision( mousePos[0], mousePos[1], 20,
                         testSphere[0][0], testSphere[0][1],
                         testSphere[1] ) )
     {
     console.log( 'collision ');
     }
     */
  
    
requestAnimationFrame(iterate);
}

/*
 Keep training the neural network to improve its accuracy
 */
async function iterate(){

    for (
let r=0r<1000; ++r)
    {
        
let posA = [ Math.random()*512Math.random()*512 ];
        
let radA Math.random() * 256;
        
        
let posB = [ Math.random()*512Math.random()*512 ];
        
let radB Math.random() * 256;
        
        var 
datain = [ posA[0],    posA[1], 
                       
radA,
                       
posB[0],    posB[1],
                       
radB ];
        
        var 
dataout = [  checkCollisionposAradAposBradB ) ];

        for (var 
i=0i<datain.lengthi++)
        {
            
datain[i] = datain[i]/512;
        }
                       
        var 
dynamicRate =  .01/(1+.0005*iteration);
        
await xactivatedatain ); 
        
await xpropagatedataoutdynamicRate );
    }

    
preview();
}

preview();


Things to Try


• Try improving the training time (different starting values for the weights and learning rates)
• Try other shapes (axis aligned shapes and orientated shapes, triangles, boxes, hexagons, ...)
• Extra intersection information (peneration distance, contact normal and contact point)


Resources and Links


• WebGPU Lab [LINK]













WebGPU by Example: Fractals, Image Effects, Ray-Tracing, Procedural Geometry, 2D/3D, Particles, Simulations WebGPU Compute graphics and animations using the webgpu api 12 week course kenwright learn webgpu api kenwright programming compute and graphics applications with html5 and webgpu api kenwright real-time 3d graphics with webgpu kenwright webgpu api develompent a quick start guide kenwright webgpu by example 2022 kenwright webgpu gems kenwright webgpu interactive compute and graphics visualization cookbook kenwright wgsl webgpu shading language cookbook kenwright wgsl webgpugems shading language cookbook kenwright



 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.