Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

Having trouble generating a voxel sphere

$
0
0

I'm trying to generate the coordinates for a sphere with a given radius, but am only managing to produce a cylinder and I'm not really figuring out why. Here's my current code:

function makeSphere(radius){
          var sphere3D = {};

          var radiusX = radius + 0.5;
          var radiusY = radius + 0.5;
          var radiusZ = radius + 0.5;

          var invRadiusX = 1 / radiusX;
          var invRadiusY = 1 / radiusY;
          var invRadiusZ = 1 / radiusZ;

          var ceilRadiusX = Math.ceil(radiusX);
          var ceilRadiusY = Math.ceil(radiusY);
          var ceilRadiusZ = Math.ceil(radiusZ);

          var nextXn = 0;
          forX: for (var x = 0; x <= ceilRadiusX; ++x) {
            var xn = nextXn;
            nextXn = (x + 1) * invRadiusX;
            var nextYn = 0;
            forY: for (var y = 0; y <= ceilRadiusY; ++y) {
              var yn = nextYn;
              nextYn = (y + 1) * invRadiusY;
              var nextZn = 0;
              forZ: for (var z = 0; z <= ceilRadiusZ; ++z) {
                var zn = nextZn;
                nextZn = (z + 1) * invRadiusZ;

                var distanceSq = lengthSq(xn, yn, zn);
                if (distanceSq > 1) {
                    if (z == 0) {
                        if (y == 0) {
                            break forX;
                        }
                        break forY;
                    }
                    break forZ;
                }


                if (lengthSq(nextXn, yn, zn) <= 1 && lengthSq(xn, nextYn, zn) <= 1 && lengthSq(xn, yn, nextZn) <= 1) {
                    continue;
                }


                  sphere3D[[x,y,z]] = true;
                sphere3D[[-x,y,z]] = true;
                sphere3D[[x,-y,z]] = true;
                sphere3D[[x,y,-z]] = true;
                sphere3D[[-x,-y,z]] = true;
                sphere3D[[x,-y,-z]] = true;
                sphere3D[[-x,y,-z]] = true;
                sphere3D[[-x,-y,-z]] = true;

              }
            }
          }
        }


        function lengthSq(x, y, z) {
            return (x * x) + (y * y) + (z * z);
        }

        function lengthSq(x, z) {
            return (x * x) + (z * z);
        }

Which gives the following output.

Any ideas on where I'm messing up? Thanks in advance for your attention.


Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>