/* ******************************************************************************
*  Function Name : instanceFile()
*
*  Description :  Instance the geometry from a BGEO file
*
*  Input Arguments : GU_Detail *file_gdp, GU_Detail *inst_gdp, GU_Detail *mb_gdp
*
*  Return Value : int
*
***************************************************************************** */
int VRAY_clusterThis::instanceFile(GU_Detail * file_gdp, GU_Detail * inst_gdp, GU_Detail * mb_gdp)
{
#ifdef DEBUG
   std::cout << "VRAY_clusterThis::instanceFile()" << std::endl;
   cout << "VRAY_clusterThis::instanceFile() myPointAttributes.geo_fname: " << myPointAttributes.geo_fname << endl;
#endif

#define USE_POINT_FNAME 1

   GU_Detail null_gdp;
   UT_Matrix4 xform(1.0);
   UT_Matrix3 rot_xform(1.0);
//   UT_XformOrder xformOrder(UT_XformOrder::SRT,  UT_XformOrder::XYZ);

#ifdef USE_POINT_FNAME
   GU_Detail * file_geo_gdp;
   file_geo_gdp = VRAY_Procedural::allocateGeometry();
   if(!file_geo_gdp->load((const char *)myPointAttributes.geo_fname).success())
      throw VRAY_clusterThis_Exception("VRAY_clusterThis::instanceFile() Failed to load geometry file ", 1);
   GU_Detail temp_gdp(file_geo_gdp);
#else
   GU_Detail temp_gdp(file_gdp);
#endif

   UT_Vector3 myDir = myPointAttributes.N;
   UT_Vector3 myUp = UT_Vector3(0, 1, 0);

// Transform the geo to the new position
   rot_xform.orient(myDir, myUp);
   xform = rot_xform;

   xform.scale(mySize[0] * myPointAttributes.pscale, mySize[1] * myPointAttributes.pscale, mySize[2] * myPointAttributes.pscale);
//    xform.rotate(myPointAttributes.N[0], myPointAttributes.N[1], myPointAttributes.N[2], xformOrder);
   xform.translate(myPointAttributes.myNewPos[0], myPointAttributes.myNewPos[1], myPointAttributes.myNewPos[2]);
//   xform.xform(xformOrder, myPointAttributes.myNewPos[0], myPointAttributes.myNewPos[1], myPointAttributes.myNewPos[2],
//               myPointAttributes.N[0], myPointAttributes.N[1], myPointAttributes.N[2],
//               mySize[0], mySize[1], mySize[2]);

   temp_gdp.transform(xform);

//   GU_Detail theFileGDP(theFiles[myPointAttributes.lod][myPointAttributes.anim_frame]);
   addFileAttributeRefs(&temp_gdp);
   setFileAttributes(&temp_gdp);

   // Run CVEX function on this instance
   if(myCVEX_Exec)
      VRAY_clusterThis::runCVEX(&temp_gdp, &null_gdp, myCVEXFname, CLUSTER_CVEX_POINT);
   if(myCVEX_Exec_prim)
      VRAY_clusterThis::runCVEX(&temp_gdp, &null_gdp, myCVEXFname_prim, CLUSTER_CVEX_PRIM);

   inst_gdp->merge(temp_gdp);


   if(myDoMotionBlur == CLUSTER_MB_DEFORMATION) {
#ifdef USE_POINT_FNAME
         GU_Detail temp_gdp(file_geo_gdp);
#else
         GU_Detail temp_gdp(file_gdp);
#endif

         xform.identity();
         rot_xform.identity();
         rot_xform.orient(myDir, myUp);
         xform = rot_xform;

         xform.scale(mySize[0] * myPointAttributes.pscale, mySize[1] * myPointAttributes.pscale, mySize[2] * myPointAttributes.pscale);
//        xform.rotate(myPointAttributes.N[0], myPointAttributes.N[1], myPointAttributes.N[2], xformOrder);
         xform.translate(myPointAttributes.myMBPos[0], myPointAttributes.myMBPos[1], myPointAttributes.myMBPos[2]);
         //   xform.xform(xformOrder, myPointAttributes.myMBPos[0], myPointAttributes.myMBPos[1], myPointAttributes.myMBPos[2],
         //               myPointAttributes.N[0], myPointAttributes.N[1], myPointAttributes.N[2],
         //               mySize[0], mySize[1], mySize[2]);

         // Run CVEX function on this instance
         if(myCVEX_Exec)
            VRAY_clusterThis::runCVEX(&temp_gdp, &null_gdp, myCVEXFname, CLUSTER_CVEX_POINT);
         if(myCVEX_Exec_prim)
            VRAY_clusterThis::runCVEX(&temp_gdp, &null_gdp, myCVEXFname_prim, CLUSTER_CVEX_PRIM);

         temp_gdp.transform(xform);
         mb_gdp->merge(temp_gdp);
      }


#ifdef USE_POINT_FNAME
   VRAY_Procedural::freeGeometry(file_geo_gdp);
#endif

   return 0;
}
예제 #2
0
/* ******************************************************************************
*  Function Name : render()
*
*  Description :   Render VRAY_clusterThis object
*
*  Input Arguments : None
*
*  Return Value : None
*
***************************************************************************** */
void VRAY_clusterThis::render()
{
   GU_Detail * gdp, *inst_gdp, *mb_gdp, *file_gdp;
   GEO_Point * ppt;

//   GEO_AttributeHandle attrHandleVelocity, attrHandleForce, attrHandleVorticity, attrHandleNormal, attrHandleNumNeighbors,
//   attrHandleTextureUV, attrHandleMass, attrHandleAge, attrHandleTemperature, attrHandleID,
//   attrHandleDensity, attrHandleViscosity, attrHandlePressure, attrHandlePscale;

   long int point_num = 0;
   static bool rendered = false;

   if(myVerbose > CLUSTER_MSG_QUIET) {
         std::cout << "VRAY_clusterThis::render() - Version: " << DCA_VERSION << std::endl;
         std::cout << "VRAY_clusterThis::render() - Built for Houdini Version: " << UT_MAJOR_VERSION
                   << "." << UT_MINOR_VERSION << "." << UT_BUILD_VERSION_INT << std::endl;
         std::cout << "VRAY_clusterThis::render() - Instancing ..." <<  endl;
      }


   try {

//          cout << "VM_GEO_clusterThis OTL version: " <<  myOTLVersion << endl;

//       if(myOTLVersion != DCA_VERSION) {
//          cout << "VM_GEO_clusterThis OTL is wrong version: " <<  myOTLVersion << ", should be version: " << DCA_VERSION << ", please install correct version." << endl;
//          throw VRAY_clusterThis_Exception ( "VRAY_clusterThis::render() VM_GEO_clusterThis OTL is wrong version!", 1 );
//       }


         if(!rendered || !myUseTempFile) {

               void * handle = VRAY_Procedural::queryObject(0);
               gdp = VRAY_Procedural::allocateGeometry();

               if(myUseGeoFile) {
                     // If the file failed to load, throw an exception
                     if(!(gdp->load((const char *)mySrcGeoFname).success()))
                        throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() - Failed to read source geometry file ", 1);

                     if(myVerbose > CLUSTER_MSG_INFO)
                        cout << "VRAY_clusterThis::render() - Successfully loaded source geo file: " << mySrcGeoFname << endl;
                  }
               else {
                     gdp->copy(*VRAY_Procedural::queryGeometry(handle, 0));
                     if(myVerbose > CLUSTER_MSG_INFO)
                        cout << "VRAY_clusterThis::render() - Copied incoming geometry" << endl;
                  }


               gdp->getBBox(&myBox);

//               std::cout << "VRAY_clusterThis::render() - gdp->getBBox(&myBox): " << myBox << std::endl;

               VRAY_Procedural::querySurfaceShader(handle, myMaterial);
               myMaterial.harden();
//         myPointAttributes.material = myMaterial;

//         const char **        getSParm (int token) const
//         cout << "VRAY_clusterThis::render() getSParm: " << *getSParm (0) << endl;


#ifdef DEBUG
               cout << "VRAY_clusterThis::render() myMaterial: " << myMaterial << endl;
#endif

               myLOD = getLevelOfDetail(myBox);
               if(myVerbose > CLUSTER_MSG_INFO)
                  cout << "VRAY_clusterThis::render() myLOD: " << myLOD << endl;


               // Get the number if points of the incoming geometery, calculate an interval for reporting the status of the instancing to the user
               long int num_points = (long int) gdp->points().entries();
               long int stat_interval = (long int)(num_points * 0.10) + 1;

               if(myVerbose > CLUSTER_MSG_QUIET)
                  cout << "VRAY_clusterThis::render() Number of points of incoming geometry: " << num_points << endl;

               myObjectName = VRAY_Procedural::queryObjectName(handle);

//      cout << "VRAY_clusterThis::render() Object Name: " << myObjectName << endl;
//      cout << "VRAY_clusterThis::render() Root Name: " << queryRootName() << endl;

// DEBUG stuff ...

//   changeSetting("object:geo_velocityblur", "on");

               UT_String      str;
               int     vblur = 0;
               import("object:velocityblur", &vblur, 0);

               if(vblur) {
                     str = 0;
                     import("velocity", str);
                     if(str.isstring()) {
//               const char  *  name;
//               name = queryObjectName(handle);
                           VRAYwarning("%s[%s] cannot get %s",
                                       VRAY_Procedural::getClassName(), (const char *)myObjectName, " motion blur attr");

                        }
                  }


               myXformInverse = queryTransform(handle, 0);
               myXformInverse.invert();




#ifdef DEBUG
               cout << "Geometry Samples: " << queryGeometrySamples(handle) << endl;
// cout << "scale: " << getFParm ( "scale" ) << endl;
#endif

               // Dump the user parameters to the console
               if(myVerbose == CLUSTER_MSG_DEBUG)
                  VRAY_clusterThis::dumpParameters();

               switch(myMethod) {
                     case CLUSTER_INSTANCE_NOW:
                        inst_gdp = VRAY_Procedural::allocateGeometry();
                        if(myDoMotionBlur == CLUSTER_MB_DEFORMATION)
                           mb_gdp = VRAY_Procedural::allocateGeometry();
                        if(myVerbose > CLUSTER_MSG_QUIET)
                           cout << "VRAY_clusterThis::render() - Using \"instance all the geometry at once\" method" << endl;
                        break;
                     case CLUSTER_INSTANCE_DEFERRED:
                        if(myVerbose > CLUSTER_MSG_QUIET)
                           cout << "VRAY_clusterThis::render() - Using \"addProcedural()\" method" << endl;
                        break;
                  }

               rendered = true;

               // Get the point's attribute offsets
               VRAY_clusterThis::getAttributeOffsets(gdp);

               // Check for required attributes
               VRAY_clusterThis::checkRequiredAttributes();

               // Check for weight attribute if the user wants metaballs
               if((myPrimType == CLUSTER_PRIM_METABALL) && (myPointAttrOffsets.weight.isInvalid())) {

                     cout << "Incoming points must have weight attribute if instancing metaballs! Throwing exception ..." << endl;
                     throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() Incoming points must have weight attribute if instancing metaballs!", 1);
                  }


               if(myPrimType == CLUSTER_FILE) {
                     file_gdp = VRAY_Procedural::allocateGeometry();
                     int file_load_stat = VRAY_clusterThis::preLoadGeoFile(file_gdp);

                     if(!file_load_stat) {
//                           myFileGDP = file_gdp;
                           if(myVerbose > CLUSTER_MSG_INFO)
                              cout << "VRAY_clusterThis::render() Successfully loaded geometry file: " << myGeoFile << endl;
                        }
                     else {
                           throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() Failed to load geometry file ", 1);
                        }
                  }

               // init some vars ...
               myPointAttributes.Cd = (UT_Vector3(1, 1, 1));
               myPointAttributes.v = (UT_Vector3(0, 0, 0));
               myPointAttributes.N = (UT_Vector3(0, 1, 0));
               myPointAttributes.Alpha = 1.0;
               myPointAttributes.pscale = 1.0;
               myPointAttributes.id = 0;

               myNoise.initialize(myNoiseSeed, myNoiseType);

               // Create the attribute "offsets" for the geometry to be instanced
               VRAY_clusterThis::createAttributeOffsets(inst_gdp, mb_gdp);

//changeSetting("surface", "constant Cd ( 1 0 0 )", "object");


               fpreal theta = (2.0 * M_PI) / myNumCopies;
               myInstanceNum = 0;

               if(myCVEX_Exec_pre) {
                     if(myVerbose > CLUSTER_MSG_INFO)
                        cout << "VRAY_clusterThis::render() Executing Pre Process CVEX code" << endl;
                     VRAY_clusterThis::runCVEX(gdp, gdp, myCVEXFname_pre, CLUSTER_CVEX_POINT);
                  }

               /// For each point of the incoming geometry
               GA_FOR_ALL_GPOINTS(gdp, ppt) {
                  myPointAttributes.myPos = ppt->getPos();

                  // get the point's attributes
                  VRAY_clusterThis::getAttributes(ppt, gdp);

#ifdef DEBUG
                  cout << "VRAY_clusterThis::render() " << "theta: " << theta << endl;
#endif

                  uint seed = 37;
                  fpreal dice;
                  bool skip = false;

                  if((myPrimType != CLUSTER_PRIM_CURVE) ||
                        ((myMethod == CLUSTER_INSTANCE_DEFERRED && (myPrimType == CLUSTER_PRIM_CURVE)))) {


                        // For each point, make a number of copies of and recurse a number of times for each copy ...
                        for(int copyNum = 0; copyNum < myNumCopies; copyNum++) {
                              for(int recursionNum = 0; recursionNum < myRecursion; recursionNum++) {

                                    // generate random number to determine to instance or not

                                    dice = SYSfastRandom(seed);
                                    (dice > myBirthProb)?skip = true:skip = false;
//                  cout << dice << " " << skip << endl;
                                    seed = uint(dice * 100);

                                    // Calculate the position for the next instanced object ...
                                    VRAY_clusterThis::calculateNewPosition(theta, copyNum, recursionNum);

                                    if(!skip) {

                                          // Instance an object ...
                                          switch(myMethod) {
                                                   // For the "create all geometry at once" method, instance the object now ...
                                                case CLUSTER_INSTANCE_NOW:
                                                   // Create a primitive based upon user's selection
                                                   // TODO: can later be driven by a point attribute
                                                   switch(myPrimType) {
                                                         case CLUSTER_POINT:
                                                            VRAY_clusterThis::instancePoint(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_SPHERE:
                                                            VRAY_clusterThis::instanceSphere(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_CUBE:
                                                            VRAY_clusterThis::instanceCube(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_GRID:
                                                            VRAY_clusterThis::instanceGrid(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_TUBE:
                                                            VRAY_clusterThis::instanceTube(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_CIRCLE:
                                                            VRAY_clusterThis::instanceCircle(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_PRIM_METABALL:
                                                            VRAY_clusterThis::instanceMetaball(inst_gdp, mb_gdp);
                                                            break;
                                                         case CLUSTER_FILE:
                                                            VRAY_clusterThis::instanceFile(file_gdp, inst_gdp, mb_gdp);
                                                            break;
                                                            // In case a instance type comes through that's not "legal", throw exception
                                                         default:
                                                            throw VRAY_clusterThis_Exception("VRAY_clusterThis::render() Illegal instance type, exiting ...", 1);
                                                            break;
                                                      }
                                                   break;

                                                   // For the "deferred instance" method, add the procedural now ...
                                                case CLUSTER_INSTANCE_DEFERRED:
                                                   VRAY_Procedural::openProceduralObject();
                                                   VRAY_clusterThisChild * child = new VRAY_clusterThisChild::VRAY_clusterThisChild(this);
                                                   VRAY_Procedural::addProcedural(child);
                                                   VRAY_Procedural::changeSetting("object:geo_velocityblur", "on");
                                                   VRAY_Procedural::closeObject();
//changeSetting("surface", "constant Cd ( 1 0 0 )", "object");
//   changeSetting("object:geo_velocityblur", "on");

                                                   break;
                                             }

                                          myInstanceNum++;

#ifdef DEBUG
                                          cout << "VRAY_clusterThis::render() - myInstanceNum: " << myInstanceNum << std::endl;
#endif
                                       }

                                 } // for number of recursions ...
                           } // for number of copies ...

                     }

                  // User wants a curve instanced on this point
                  if((myPrimType == CLUSTER_PRIM_CURVE) && (myMethod == CLUSTER_INSTANCE_NOW) && (!skip))
                     VRAY_clusterThis::instanceCurve(inst_gdp, mb_gdp, theta, point_num);

                  // Increment our point counter
                  point_num++;

                  // Print out stats to the console
                  if(myVerbose > CLUSTER_MSG_INFO && (myPrimType != CLUSTER_PRIM_CURVE))
                     if((long int)(point_num % stat_interval) == 0)
                        cout << "VRAY_clusterThis::render() Number of points processed: " << point_num << " Number of instances: " << myInstanceNum << endl;

               } // for all points ...


               if(myVerbose > CLUSTER_MSG_QUIET)
                  if(myMethod == CLUSTER_INSTANCE_NOW)
                     if(myDoMotionBlur == CLUSTER_MB_DEFORMATION)
                        cout << "VRAY_clusterThis::render() - Memory usage(MB): " <<
                             (fpreal)(inst_gdp->getMemoryUsage() + mb_gdp->getMemoryUsage() / (1024.0 * 1024.0)) << endl;
                     else
                        cout << "VRAY_clusterThis::render() - Memory usage(MB): " <<
                             (fpreal)(inst_gdp->getMemoryUsage() / (1024.0 * 1024.0)) << endl;

               // If the "instance all the geo at once method" is used, add the the instanced geo for mantra to render ...
               switch(myMethod) {
                     case CLUSTER_INSTANCE_NOW:

                        if(myCVEX_Exec_post) {
                              if(myVerbose > CLUSTER_MSG_INFO)
                                 cout << "VRAY_clusterThis::render() Executing Post Process CVEX code" << endl;
                              VRAY_clusterThis::runCVEX(inst_gdp, mb_gdp, myCVEXFname_post, CLUSTER_CVEX_POINT);
                           }
                        VRAY_Procedural::openGeometryObject();
                        VRAY_Procedural::addGeometry(inst_gdp, 0.0);

                        if(myDoMotionBlur == CLUSTER_MB_VELOCITY)
                           VRAY_Procedural::addVelocityBlurGeometry(inst_gdp, myShutter, myShutter2);

// float    addVelocityBlurGeometry (GU_Detail *gdp, fpreal pre_blur, fpreal post_blur, const char *velocity_attribute="v")

                        if(myDoMotionBlur == CLUSTER_MB_DEFORMATION)
                           VRAY_Procedural::addGeometry(mb_gdp, myShutter);

                        VRAY_Procedural::setComputeN(1);
//                        setSurface(myMaterial);
                        VRAY_Procedural::closeObject();

                        break;
                     case CLUSTER_INSTANCE_DEFERRED:
                        break;
                  }

               if(myVerbose > CLUSTER_MSG_QUIET && (myPrimType != CLUSTER_PRIM_CURVE))
                  cout << "VRAY_clusterThis::render() Total number of instances: " << myInstanceNum << endl;

               // Save the geo to temp location so it doesn't have to be regenerated for a deep shadow pass, etc.
               if(myMethod == CLUSTER_INSTANCE_NOW && myUseTempFile) {
                     ofstream myGeoStream;
                     // myGeoStream.open("/tmp/thisGeo.bgeo");
                     myGeoStream.open((const char *)myTempFname, ios_base::binary);
                     UT_Options myOptions;
                     inst_gdp->save(myGeoStream, 1, &myOptions);
                     myGeoStream.flush();
                     myGeoStream.close();
                     if(myVerbose > CLUSTER_MSG_QUIET)
                        cout << "VRAY_clusterThis::render() - Saved geometry to temp file: " << myTempFname << endl;
                  }

               if(myPrimType == CLUSTER_FILE)
                  VRAY_Procedural::freeGeometry(file_gdp);

               // We're done, free the original geometry
               VRAY_Procedural::freeGeometry(gdp);

            } /// if (rendered) ...
예제 #3
0
/* ******************************************************************************
*  Function Name : initialize
*
*  Description :  Initialize the VRAY_clusterThis object
*
*  Input Arguments : const UT_BoundingBox *
*
*  Return Value : int
*
***************************************************************************** */
int VRAY_clusterThis::initialize(const UT_BoundingBox * box)
{
   if(myVerbose > CLUSTER_MSG_INFO)
      std::cout << "VRAY_clusterThis::initialize()" << std::endl;

   void   *   handle;
   const char  *  name;
   UT_BoundingBox tbox, tvbox;
   UT_Matrix4     xform;
   UT_String      str;

   myInitTime = std::clock();
   std::time(&myInitStartTime);

   // Get the OTL parameters
   VRAY_clusterThis::getOTLParameters();

   if(myVerbose > CLUSTER_MSG_QUIET) {
         std::cout << std::endl << "VRAY_clusterThis::initialize() - Version: "
                   << MAJOR_VER << "." << MINOR_VER << "." << BUILD_VER << std::endl;
         std::cout << "VRAY_clusterThis::initialize() - Built for Houdini Version: "
                   << UT_MAJOR_VERSION << "." << UT_MINOR_VERSION << "." << UT_BUILD_VERSION_INT << std::endl;
         std::cout << "VRAY_clusterThis::initialize() - Initializing ..." <<  std::endl;
      }

//          cout << "VM_GEO_clusterThis OTL version: " <<  myOTLVersion << std::endl;
//       if(myOTLVersion != DCA_VERSION) {
//          cout << "VM_GEO_clusterThis OTL is wrong version: " <<  myOTLVersion << ", should be version: " << DCA_VERSION << ", please install correct version." << std::endl;
//          throw VRAY_clusterThis_Exception ( "VRAY_clusterThis::initialize() VM_GEO_clusterThis OTL is wrong version!", 1 );
//       }


   // Dump the user parameters to the console
   if(myVerbose == CLUSTER_MSG_DEBUG)
      VRAY_clusterThis::dumpParameters();


   // Find the geometry object to render
//   name = 0;
//   if(VRAY_Procedural::import("object", str))
//      name = str.isstring() ? (const char *)str : 0;
////   handle = VRAY_Procedural::queryObject(name);
//   handle = VRAY_Procedural::queryObject(0);
//   if(!handle) {
//         VRAYerror("%s couldn't find object '%s'", VRAY_Procedural::getClassName(), name);
//         return 0;
//      }
//   name = VRAY_Procedural::queryObjectName(handle);
//
////   std::cout << "VRAY_clusterThis::initialize() name: " << name << std::endl;
//
//   myGdp = (GU_Detail *)VRAY_Procedural::queryGeometry(handle, 0);
//   if(!myGdp) {
//         VRAYerror("%s object '%s' has no geometry", VRAY_Procedural::getClassName(), name);
//         return 0;
//      }



   handle = VRAY_Procedural::queryObject(0);
   myGdp = VRAY_Procedural::allocateGeometry();

   if(myUseGeoFile) {
         // If the file failed to load, throw an exception
         if(!(myGdp->load((const char *)mySrcGeoFname).success()))
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::initialize() - Failed to read source geometry file ", 1);

         if(myVerbose > CLUSTER_MSG_INFO)
            cout << "VRAY_clusterThis::initialize() - Successfully loaded source geo file: " << mySrcGeoFname << endl;
      }
   else {
         myGdp->copy(*VRAY_Procedural::queryGeometry(handle, 0));
         if(myVerbose > CLUSTER_MSG_INFO)
            cout << "VRAY_clusterThis::initialize() - Copied incoming geometry" << endl;
      }


   // Get the point's attribute references
   VRAY_clusterThis::getAttributeRefs(myGdp);

   // Check for required attributes
   VRAY_clusterThis::checkRequiredAttributes();

   myNumSourcePoints = (long int) myGdp->points().entries();

   VRAY_Procedural::querySurfaceShader(handle, myMaterial);
   myMaterial.harden();
//         myPointAttributes.material = myMaterial;

#ifdef DEBUG
   cout << "VRAY_clusterThis::initialize() myMaterial: " << myMaterial << std::endl;
#endif

   myObjectName = VRAY_Procedural::queryObjectName(handle);

//      cout << "VRAY_clusterThis::initialize() Object Name: " << myObjectName << std::endl;
//      cout << "VRAY_clusterThis::initialize() Root Name: " << queryRootName() << std::endl;

#ifdef DEBUG
   cout << "Geometry Samples: " << queryGeometrySamples(handle) << std::endl;
#endif


//   if(import("object:name", str)) {
//         cout << "object:name: " << str << std::endl;
//      }
//
//   if(import("object:surface", str)) {
//         cout << "object:surface: " << str << std::endl;
//      }
//
//   if(import("plane:variable", str)) {
//         cout << "plane:variable: " << str << std::endl;
//      }
//
//   if(import("image:resolution", str)) {
//         cout << "image:resolution: " << str << std::endl;
//      }
//
//   if(import("object:categories", str)) {
//         cout << "object:categories: " << str << std::endl;
//      }
//
//   if(import("object:renderpoints", str)) {
//         cout << "object:renderpoints: " << str << std::endl;
//      }



//   changeSetting("object:geo_velocityblur", "on");

//   int     vblur = 0;
//   import("object:velocityblur", &vblur, 0);
//
//   if(vblur) {
//         str = 0;
//         import("velocity", str);
//         if(str.isstring()) {
////               const char  *  name;
////               name = queryObjectName(handle);
//               VRAYwarning("%s[%s] cannot get %s",
//                           VRAY_Procedural::getClassName(), (const char *)myObjectName, " motion blur attr");
//
//            }
//      }



   myXformInverse = queryTransform(handle, 0);
   myXformInverse.invert();


   if(myPostProcess && myVDBPostProcess)
      VRAY_clusterThis::buildVDBGrids(myGdp);

   // find how much noise is being generated to help with BBox calculations
   fpreal noise_bias;

   if(myNoiseType < 4) {
         myNoise.setSeed(myPointAttributes.id);
         noise_bias = (myNoise.turbulence(myPointAttributes.myPos, myFractalDepth, myRough, myNoiseAtten) * myNoiseAmp) + 1.0;
      }
   else {
         myMersenneTwister.setSeed(myPointAttributes.id);
         noise_bias = (myMersenneTwister.frandom() * myNoiseAmp) + 1.0;
      }

#ifdef DEBUG
   cout << "VRAY_clusterThis::initialize() " << "noise_bias: " << noise_bias << endl;
#endif


   // Calculate our BBox for the incoming point cloud and add noise, radius, etc. to enlarge the BBox to
   // accomodate the instanced geometry
   // Build the geo point tree to be used for nearest neighbor caculations
   fpreal scale;
   fpreal radius;
   fpreal pscale;
   int first = 1;
   xform = myXformInverse;

   for(uint32 i = myGdp->points().entries(); i-- > 0;) {
         GEO_Point * ppt = myGdp->points()(i);

//         // Append to our list of points to be used for various tasks,
//         // like breaking up the point cloud into regular grids, etc.
//         mySRCPointList.append(i);

         if(myUsePointRadius)
            radius = static_cast<fpreal>(ppt->getValue<fpreal>(myPointAttrRefs.radius, 0));
         else
            radius = myRadius;

         pscale = static_cast<fpreal>(ppt->getValue<fpreal>(myPointAttrRefs.pscale, 0));

         if(myUsePointRadius)
            scale = (radius + noise_bias) * pscale;
         else
            scale = (myRadius + noise_bias) * pscale;

         mySRCPointTree.appendPtRadius(myGdp, ppt, radius);

         getRoughBBox(tbox, tvbox, ppt, scale, myPointAttrRefs.v, myTimeScale, xform);
         if(first) {
               myBox = tbox;
               myVelBox = tvbox;
               first = 0;
            }
         else {
               myBox.enlargeBounds(tbox);
               myVelBox.enlargeBounds(tvbox);
            }

      }

   if(first) {
         std::cout << "VRAY_clusterThis::initialize() " << getClassName() << " found no points in: " << name << std::endl;
         VRAYwarning("VRAY_clusterThis::initialize() %s found no points in %s", getClassName(), name);
         return 0;
      }


//   std::cout << "VRAY_clusterThis::initialize() *** \nmyBox: " << myBox << "myVelBox: " << myVelBox << std::endl;

   // NOTE: Enlarge the bbox another x% because we won't be able to give mantra the actual bbox size via render() method.
   // (mantra calls getBoundingBox() only once, and it's before the render() method is called by mantra).
   myBox.enlargeBounds(myBBoxFudgeFactor);
   myVelBox.enlargeBounds(myBBoxFudgeFactor);

//   myBox.enlargeFloats();
//   myVelBox.enlargeFloats();

   for(int i = 0; i < 3; i++)
      for(int j = 0; j < 2; j++) {
            if(myBox.vals[i][j] <= CLUSTER_BBOX_MIN) {
//            if(SYSisNan(myBox.vals[i][j])) {
//            if(myBox.vals[i][j] <= std::numeric_limits<float>::min()) {
                  myBox.vals[i][j] = CLUSTER_BBOX_MIN;
                  if(myVerbose == CLUSTER_MSG_DEBUG)
                     std::cout << "VRAY_clusterThis::initialize() found NAN: " << myBox.vals[i][j] << std::endl;
               }
         }


   if(myVerbose == CLUSTER_MSG_DEBUG)
      std::cout << "VRAY_clusterThis::initialize()\nmyBox: " << myBox << "myVelBox: " << myVelBox << std::endl;


   if(box) {
         if(myPointAttrRefs.v.isValid()) {
               if(testClampBox(myBox, *box) || testClampBox(myVelBox, *box))
                  VRAYwarning("%s[%s] cannot render a partial box %s", getClassName(), name, "with motion blur");
               std::cout << "VRAY_clusterThis::initialize() " << getClassName() << " WARNING: cannot render a partial box " << name << std::endl;
            }
         else {
               clampBox(myBox, *box);
               clampBox(myVelBox, *box);
            }
      }

//   std::cout << "VRAY_clusterThis::initialize() 3 \nmyBox: " << myBox << "myVelBox: " << myVelBox << std::endl;
//   if(box) {
//         std::cout << "VRAY_clusterThis::initialize() box min: " << box->xmin() << " " << box->ymin() << " " << box->zmin() << std::endl;
//         std::cout << "VRAY_clusterThis::initialize() box max: " << box->xmax() << " " << box->ymax() << " " << box->zmax() << std::endl;
//      }


   myPointTreeMemUsage = mySRCPointTree.getMemoryUsage();

   if(myVerbose == CLUSTER_MSG_DEBUG)
      std::cout << "VRAY_clusterThis::initialize() myPointTreeMemUsage: " << myPointTreeMemUsage << std::endl;


   std::time(&myInitEndTime);
   myInitExecTime = std::clock() - myInitTime;
   cout << "VRAY_clusterThis::initialize() " << "myInitExecTime: " << myInitExecTime << endl;


   return 1;
}
void VRAY_clusterThis::preProcess(GU_Detail * gdp)

{

   GEO_Point * ppt;

   long int num_points = (long int) gdp->points().entries();
   long int stat_interval = (long int)(num_points * 0.10) + 1;


   for(uint32 i = gdp->points().entries(); i-- > 0;) {
         ppt = gdp->points()(i);

         myPointList.append(i);

      }



   // If the user wants to build grids for pre processing
   // TODO: Should this be an option?  There may be functions/features that will depend on this ... discuss!
   if(!myPreProcess)
      return;

   if(myVerbose > CLUSTER_MSG_INFO)
      cout << "VRAY_clusterThis::preProcess() Pre Processing Voxels" << std::endl;

//                     openvdb::ScalarGrid::Accessor accessor;
//                     openvdb::FloatTree myTree;
   openvdb::FloatTree::ConstPtr myGeoTreePtr;
   openvdb::VectorTree::ConstPtr myGeoGradTreePtr;

   ParticleList paGeoList(gdp, myPreVDBRadiusMult, myPreVDBVelocityMult);
   openvdb::tools::PointSampler myGeoSampler, geoGradSampler;
//                     openvdb::tools::GridSampling<openvdb::FloatTree>  myGridSampler;

   if(myVerbose == CLUSTER_MSG_DEBUG)
      std::cout << "VRAY_clusterThis::preProcess() paGeoList.size() ... "  << paGeoList.size() << std::endl;

   if(paGeoList.size() != 0) {

         hvdb::Interrupter boss("VRAY_clusterThis::preProcess() Converting particles to level set");

         Settings settings;
         settings.mRadiusMin = myPreRadiusMin;
         settings.mRasterizeTrails = myPreRasterType;
         settings.mDx = myPreDx;  // only used for rasterizeTrails()
         settings.mFogVolume = myPreFogVolume;
         settings.mGradientWidth = myPreGradientWidth;  // only used for fog volume

         float background;

         // background in WS units
         if(myPreWSUnits)
            background = myPreBandWidth;
         // background NOT in WS units
         else
            background = myPreVoxelSize * myPreBandWidth;

         // Construct a new scalar grid with the specified background value.
         openvdb::math::Transform::Ptr transform =
            openvdb::math::Transform::createLinearTransform(myPreVoxelSize);

//         openvdb::ScalarGrid::Ptr myGeoGrid = openvdb::ScalarGrid::create(background);

         myGeoGrid = openvdb::ScalarGrid::create(background);

         myGeoGrid->setTransform(transform);
         myGeoGrid->setGridClass(openvdb::GRID_LEVEL_SET);

         // Perform the particle conversion.
         this->convert(myGeoGrid, paGeoList, settings, boss);

         if(myVerbose == CLUSTER_MSG_DEBUG) {
               std::cout << "VRAY_clusterThis::preProcess() - activeVoxelCount(): "
                         << myGeoGrid->activeVoxelCount() << std::endl;
               std::cout << "VRAY_clusterThis::preProcess() - background: "
                         << myGeoGrid->background() << std::endl;
            }

         // Insert the new grid into the ouput detail.
         UT_String gridNameStr = "ClusterGrid";
         myGeoGrid->insertMeta("float type", openvdb::StringMetadata("averaged_velocity"));
         myGeoGrid->insertMeta("name", openvdb::StringMetadata((const char *)gridNameStr));
         myGeoGrid->insertMeta("VoxelSize", openvdb::FloatMetadata(myPreVoxelSize));
         myGeoGrid->insertMeta("background", openvdb::FloatMetadata(background));


         UT_Vector3 pos, seed_pos, currVel;
//         const GA_PointGroup * sourceGroup = NULL;
         long int pt_counter = 0;
         float radius = 5.0f;

         if(myVerbose > CLUSTER_MSG_INFO)
            std::cout << "VRAY_clusterThis::preProcess() - Massaging data ... " << std::endl;

         long int pointsFound = 0;
         GEO_AttributeHandle inst_vel_gah = gdp->getPointAttribute("v");
         GEO_AttributeHandle source_vel_gah = gdp->getPointAttribute("v");
         GEO_AttributeHandle inst_N_gah = gdp->getPointAttribute("N");
         GEO_AttributeHandle source_N_gah = gdp->getPointAttribute("N");
         GEO_AttributeHandle inst_Cd_gah = gdp->getPointAttribute("Cd");
         GEO_AttributeHandle source_Cd_gah = gdp->getPointAttribute("Cd");
         GEO_AttributeHandle inst_Alpha_gah = gdp->getPointAttribute("Alpha");
         GEO_AttributeHandle source_Alpha_gah = gdp->getPointAttribute("Alpha");

         if(!inst_vel_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Instance velocity handle invalid, exiting ...", 1);
         if(!source_vel_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Source velocity handle invalid, exiting ...", 1);
         if(!inst_N_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Instance normal handle invalid, exiting ...", 1);
         if(!source_N_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Source normal handle invalid, exiting ...", 1);
         if(!inst_Cd_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Instance color handle invalid, exiting ...", 1);
         if(!source_Cd_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Source color handle invalid, exiting ...", 1);
         if(!inst_Alpha_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Instance alpha handle invalid, exiting ...", 1);
         if(!source_Alpha_gah.isAttributeValid())
            throw VRAY_clusterThis_Exception("VRAY_clusterThis::preProcess() Source alpha handle invalid, exiting ...", 1);

         openvdb::FloatTree::ValueType sampleResult;
         openvdb::VectorGrid::ValueType gradResult;
         const openvdb::FloatTree aTree;
         openvdb::FloatTree& myGeoTree = myGeoGrid->treeRW();

         openvdb::tools::Filter<openvdb::FloatGrid> preProcessFilter(*myGeoGrid);
//                           openvdb::tools::Filter<openvdb::FloatGrid> barFilter(myGeoGrid);

         if(myPreVDBMedianFilter)
            preProcessFilter.median();

         if(myPreVDBMeanFilter)
            preProcessFilter.mean();

         if(myPreVDBMeanCurvatureFilter)
            preProcessFilter.meanCurvature();

         if(myPreVDBLaplacianFilter)
            preProcessFilter.laplacian();

//                           if(myVDBReNormalizeFilter)
//                              float r = barFilter.renormalize(3, 0.1);

         if(myPreVDBOffsetFilter)
            preProcessFilter.offset(myPreVDBOffsetFilterAmount);


         myGradientGrid = openvdb::VectorGrid::create();
//         openvdb::VectorGrid::Ptr myGradientGrid = openvdb::VectorGrid::create();
         myGradientGrid->setTransform(transform);
//               myGradientGrid->setGridClass(openvdb::GRID_FOG_VOLUME );
         myGradientGrid->setGridClass(openvdb::GRID_LEVEL_SET);

         openvdb::tools::Gradient<openvdb::ScalarGrid> myGradient(*myGeoGrid);
         myGradientGrid = myGradient.process();
         openvdb::VectorTree& myGeoGradTree = myGradientGrid->treeRW();

         gridNameStr = "ClusterGradientGrid";
         myGradientGrid->insertMeta("vector type", openvdb::StringMetadata("covariant (gradient)"));
         myGradientGrid->insertMeta("name", openvdb::StringMetadata((const char *)gridNameStr));
         myGradientGrid->insertMeta("VoxelSize", openvdb::FloatMetadata(myPreVoxelSize));
         myGradientGrid->insertMeta("background", openvdb::FloatMetadata(background));


         GA_FOR_ALL_GPOINTS(gdp, ppt) {
//                              myCurrPtOff = ppt->getMapOffset();
//                              std::cout << "myCurrPtOff: " << myCurrPtOff << std::endl;

            pos = ppt->getPos();

// Vec3d worldToIndex   (  const Vec3d &     xyz    )    const

//                              openvdb::Vec3R theIndex =
//                                 (openvdb::Vec3R(pos[0], pos[1], pos[2]));
            openvdb::Vec3R theIndex =
               myGeoGrid->worldToIndex(openvdb::Vec3R(pos[0], pos[1], pos[2]));

            radius = static_cast<fpreal>(ppt->getValue<fpreal>(myInstAttrRefs.pointVDBRadius, 0));
//                                    std::cout << "radius: " << radius << std::endl;

// static bool    sample (const TreeT &inTree, const Vec3R &inCoord, typename TreeT::ValueType &sampleResult)
            const openvdb::Vec3R  inst_sample_pos(theIndex[0], theIndex[1], theIndex[2]);

            bool success = myGeoSampler.sample(myGeoTree, inst_sample_pos, sampleResult);

            geoGradSampler.sample(myGeoGradTree, inst_sample_pos, gradResult);
//
//                              std::cout << "success: " << success << "\tpos: " << pos
//                                        << "\tinst_sample_pos: " << inst_sample_pos
//                                        << "\tsampleResult: " << sampleResult << std::endl;

//ValueType    sampleWorld (const Vec3R &pt) const
//ValueType    sampleWorld (Real x, Real y, Real z) const

            // if the instanced point is within the vdb volume
            if(success) {
//                                    std::cout << "pos: " << pos << " inst_sample_pos: "
//                                              << inst_sample_pos << " sampleResult: " << sampleResult
//                                              << " gradResult: " << gradResult << std::endl;
//                                    float weight;
                  pointsFound++;

                  inst_vel_gah.setElement(ppt);
                  currVel = inst_vel_gah.getV3();

                  UT_Vector3 gradVect = UT_Vector3(gradResult[0], gradResult[1], gradResult[2]);

                  ppt->setPos(pos + (myPrePosInfluence *(sampleResult * gradVect)));
//                                    ppt->setPos(pos + (sampleResult * myPosInfluence *(currVel / myFPS)));

//                                    inst_vel_gah.setV3(currVel * ((1 / sampleResult) * radius));
                  inst_vel_gah.setV3(currVel + (myPreVelInfluence *(sampleResult * gradVect)));

//                                    std::cout << "currVel: " << currVel << " sampleResult " << sampleResult
//                                              << " new vel: " <<  currVel * sampleResult << std::endl;

                  inst_N_gah.setV3(inst_N_gah.getV3() + (myPreNormalInfluence *(sampleResult * gradVect)));

//                        inst_Cd_gah.setElement(ppt);
//                        inst_Cd_gah.setV3(inst_Cd_gah.getV3() * abs(sampleResult));
//
//
//                        inst_Alpha_gah.setElement(ppt);
//                        inst_Alpha_gah.setF(inst_Alpha_gah.getF() * abs(sampleResult));

               } // if the instanced point is within the vdb volume

            if(myVerbose == CLUSTER_MSG_DEBUG) {
                  pt_counter++;
                  if((long int)(pt_counter % (stat_interval * myNumCopies * myRecursion)) == 0) {
                        cout << "VRAY_clusterThis::preProcess() Number of points pre processed: " << pt_counter
                             << "\t - Number of points found in vdb grid: " << pointsFound << std::endl;
                     }
               }

         }