three-mesh-bvh - npm

文章推薦指數: 80 %
投票人數:10人

three-mesh-bvh. TypeScript icon, indicating that this package has built-in type declarations · Keywords. three-mesh-bvh0.5.12 • Public • Published6hoursagoReadmeExploreBETA0Dependencies31Dependents33Versions three-mesh-bvh ABVHimplementationtospeedupraycastingandenablespatialqueriesagainstthree.jsmeshes. Casting500raysagainstan80,000polygonmodelat60fps! Examples Raycasting Skinnedgeometry Pointcloudinteresection Shapeintersection Geometryedgeintersection WebWorkergeneration BVHoptionsinspector Tools Sculpting Distancecomparison Trianglepainting Lassoselection Clippededges Geometryvoxelization Geometryedgeprojection Games Spherephysicscollision Playermovement PathTracing SimpleGPUPathTracing LambertGPUPathTracing CPUPathTracing ExternalProjects three-gpu-pathtracer Use Usingpre-madefunctions //ImportviaES6modules import*asTHREEfrom'three'; import{computeBoundsTree,disposeBoundsTree,acceleratedRaycast}from'three-mesh-bvh'; //OrUMD const{computeBoundsTree,disposeBoundsTree,acceleratedRaycast}=window.MeshBVHLib; //Addtheextensionfunctions THREE.BufferGeometry.prototype.computeBoundsTree=computeBoundsTree; THREE.BufferGeometry.prototype.disposeBoundsTree=disposeBoundsTree; THREE.Mesh.prototype.raycast=acceleratedRaycast; //GenerategeometryandassociatedBVH constgeom=newTHREE.TorusKnotBufferGeometry(10,3,400,100); constmesh=newTHREE.Mesh(geom,material); geom.computeBoundsTree(); OrmanuallybuildingtheBVH //ImportviaES6modules import*asTHREEfrom'three'; import{MeshBVH,acceleratedRaycast}from'three-mesh-bvh'; //OrUMD const{MeshBVH,acceleratedRaycast}=window.MeshBVHLib; //Addtheraycastfunction.AssumestheBVHisavailableon //the`boundsTree`variable THREE.Mesh.prototype.raycast=acceleratedRaycast; //... //GeneratetheBVHandusethenewlygeneratedindex geom.boundsTree=newMeshBVH(geom); Andthenraycasting //Setting"firstHitOnly"totruemeanstheMesh.raycastfunctionwillusethe //bvh"raycastFirst"functiontoreturnaresultmorequickly. constraycaster=newTHREE.Raycaster(); raycaster.firstHitOnly=true; raycaster.intersectObjects([mesh]); QueryingtheBVHDirectly import*asTHREEfrom'three'; import{MeshBVH,acceleratedRaycast}from'three-mesh-bvh'; letmesh,geometry; constinvMat=newTHREE.Matrix4(); //instantiatethegeometry //... constbvh=newMeshBVH(geometry); invMat.copy(mesh.matrixWorld).invert(); //raycasting //ensuretherayisinthelocalspaceofthegeometrybeingcastagainst raycaster.ray.applyMatrix4(invMat); consthit=bvh.raycastFirst(raycaster.ray); //resultsarereturnedinlocalspac,aswell,sotheymustbetransformedinto //worldspaceifneeded. hit.point.applyMatrixWorld(mesh.matrixWorld); //spherecasting //ensurethesphereisinthelocalspaceofthegeometrybeingcastagainst sphere.applyMatrix4(invMat); constintersects=bvh.intersectsSphere(sphere); WithSkinnedandMorphTargetMeshes import{StaticGeometryGenerator}from'three-mesh-bvh'; constgenerator=newStaticGeometryGenerator([...skinnedMeshes]); constgeometry=generator.generate(); geometry.computeBoundsTree(); //... //updatethegeometryinplace generator.generate(geometry); geometry.boundsTree.refit(); SerializationandDeserialization constgeometry=newKnotBufferGeometry(1,0.5,40,10); constbvh=newMeshBVH(geometry); constserialized=MeshBVH.serialize(bvh); //... constdeserializedBVH=MeshBVH.deserialize(serialized,geometry); geometry.boundsTree=deserializedBVH; AsynchronousGeneration NOTEWebWorkersyntaxisinconsistentlysupportedacrossbundlersandsometimesnotsupportedatallsotheGenerateMeshBVHWorkerclassisnotexportedfromthepackageroot.Ifneededthecodefromsrc/workercanbecopiedandmodifiedtoaccomodateaparticularbuildprocess. import{GenerateMeshBVHWorker}from'three-mesh-bvh/src/workers/GenerateMeshBVHWorker.js'; //... constgeometry=newKnotBufferGeometry(1,0.5,40,10); constworker=newGenerateMeshBVHWorker(); worker.generate(geometry).then(bvh=>{ geometry.boundsTree=bvh; }); BVHRaycastinginaShader SeetheshaderimplementationinthesimpleGPUPathTracingexampleforanexampleonhowtoperformBVHrayqueriesinashader. Exports SplitStrategyConstants CENTER OptionforsplittingeachBVHnodedownthecenterofthelongestaxisofthebounds. Thisisthefastestconstructionoptionandwillyieldagood,performantbounds. AVERAGE OptionforsplittingeachBVHnodeattheaveragepointalongthelongestaxisforalltrianglecentroidsinthebounds. ThisstrategymaybebetterthanCENTERwithsomegeometry. SAH OptiontouseaSurfaceAreaHeuristictosplittheboundsmoreoptimally.ThisSAHimplementationtests32discretesplitsineachnodealongeachaxistodeterminewhichsplitisthelowestcost. Thisistheslowestconstructionoptionbutwillyieldthebestboundsofthethreeoptionsandusetheleastmemory. ShapecastIntersectionConstants NOT_INTERSECTED Indicatestheshapedidnotintersectthegivenboundingbox. INTERSECTED Indicatestheshapedidintersectthegivenboundingbox. CONTAINED Indicatetheshapeentirelycontainsthegivenboundingbox. MeshBVH TheMeshBVHgenerationprocessmodifiesthegeometry'sindexbufferAttributeinplacetosavememory.TheBVHconstructionwillusethegeometry'sboundingBoxifitexistsorsetitifitdoesnot.TheBVHwillnolongerworkcorrectlyiftheindexbufferismodified. NotethatallqueryfunctionsexpectargumentsinlocalspaceoftheBVHandreturnresultsinlocalspace,aswell.Ifworldspaceresultsareneededtheymustbetransformedintoworldspaceusingobject.matrixWorld. static.serialize staticserialize(bvh:MeshBVH,options:Object=null):SerializedBVH Generatesarepresentationofthecompleteboundstreeandthegeometryindexbufferwhichcanbeusedtorecreateaboundstreeusingthedeserializefunction.TheserializeanddeserializefunctionscanbeusedtogenerateaMeshBVHasynchronouslyinabackgroundwebworkertopreventthemainthreadfromstuttering.TheBVHrootsbufferstoredintheserializedrepresentationarethesameastheonesusedbytheoriginalBVHsotheyshouldnotbemodified.IfSharedArrayBuffersareusedthenthesameBVHmemorycanbeusedformultipleBVHinmultipleWebWorkers. bvhistheMeshBVHtobeserialized.Theoptionsobjectcanhavethefollowingfields: { //iftruethenacloneofthe`geometry.index.array`andMeshBVHbuffersaremadewhichslightlyslowerbut //ensuresmodificationsdonotaffecttheserializedcontent.Canbesetto"false"ifitisguaranteedthat //nomodificationswillbemade,tosavememory,ortransferandsharethemacrossWebWorkersifSharedArrayBuffers //arebeingused. cloneBuffers:true } static.deserialize staticdeserialize(data:SerializedBVH,geometry:BufferGeometry,options:Object=null):MeshBVH ReturnsanewMeshBVHinstancefromtheserializeddata.geometryisthegeometryusedtogeneratetheoriginalBVHdatawasderivedfrom.TherootbuffersstoredindataaresetdirectlyonthenewBVHsothememoryisshared. Theoptionsobjectcanhavethefollowingfields: { //Iftruethenthebufferforthe`geometry.index`attributeissetfromtheserialized //dataattributeorcreatedifanindexdoesnotexist. setIndex:true, } NOTE:InorderfortheboundstreetobeusedforcaststhegeometryindexattributemustbereplacedbythedataintheSeralizedMeshBVHobject. .constructor constructor(geometry:BufferGeometry,options:Object) Constructstheboundstreeforthegivengeometryandproducesanewindexattributebuffer.Areferencetothepassedgeometryisretained.Theavailableoptionsare { //WhichsplitstrategytousewhenconstructingtheBVH. strategy:CENTER, //Themaximumdepthtoallowthetreetobuildto. //Settingthistoasmallertradesraycastspeedforbetterconstruction //timeandlessmemoryallocation. maxDepth:40, //Thenumberoftrianglestoaimforinaleafnode.Settingthistoalower //numbercanimproveraycastperformancebutincreaseconstructiontimeand //memoryfootprint. maxLeafTris:10, //IftruethentheboundingboxforthegeometryissetoncetheBVH //hasbeenconstructed. setBoundingBox:true, //IftruethentheMeshBVHwilluseSharedArrayBufferratherthanArrayBufferwhen //initializingtheBVHbuffers.Geometryindexdatawillbecreatedasa //SharedArrayBufferonlyifitneedstobecreated.Otherwiseitisusedas-is. useSharedArrayBuffer:false, //Anoptionalfunctionthattakesa"progress"argumentintherange[0,1] //indicatingtheprogressalongBVHgeneration.Usefulprimarilywhengenerating //theBVHasynchronouslywiththeGenerateMeshBVHWorkerclass. onProgress:null, //Printoutwarningsencounteredduringtreeconstruction. verbose:true, } NOTE:Thegeometry'sindexattributearrayismodifiedinordertobuildtheboundstree.Ifthegeometryhasnoindexthenoneisadded. .raycast raycast(ray:Ray,side:FrontSide|BackSide|DoubleSide=FrontSide):Array raycast(ray:Ray,material:Array|Material):Array Returnsallraycasttrianglehitsinunsortedorder.ItisexpectedthatrayisintheframeoftheBVHalready.LikewisethereturnedresultsarealsoprovidedinthelocalframeoftheBVH.Thesideidentifierisusedtodeterminethesidetocheckwhenraycastingoramaterialwiththegivensidefieldcanbepassed.Ifanarrayofmaterialsisprovidedthenitisexpectedthatthegeometryhasgroupsandtheappropriatematerialsideisusedpergroup. Notethatunlikethree.js'RaycasterresultsthepointsanddistancesintheintersectionsreturnedfromthisfunctionarerelativetothelocalframeoftheMeshBVH.WhenusingtheacceleratedRaycastfunctionasanoverrideforMesh.raycasttheyaretransformedintoworldspacetobeconsistentwiththree'sresults. .raycastFirst raycastFirst(ray:Ray,side:FrontSide|BackSide|DoubleSide=FrontSide):RaycastHit raycastFirst(ray:Ray,material:Array|Material):RaycastHit Returnsthefirstraycasthitinthemodel.Thisistypicallymuchfasterthanreturningallhits.Seeraycastforinformationonthesideandmaterialoptionsaswellastheframeofthereturnedintersections. .intersectsSphere intersectsSphere(sphere:Sphere):Boolean Returnswhetherornotthemeshinstersectsthegivensphere. .intersectsBox intersectsBox(box:Box3,boxToBvh:Matrix4):Boolean Returnswhetherornotthemeshintersectsthegivenbox. TheboxToBvhparameteristhetransformoftheboxinthemeshsframe. .intersectsGeometry intersectsGeometry(geometry:BufferGeometry,geometryToBvh:Matrix4):Boolean Returnswhetherornotthemeshintersectsthegivengeometry. ThegeometryToBvhparameteristhetransformofthegeometryintheBVH'slocalframe. PerformanceimprovesconsiderablyiftheprovidedgeometryalsohasaboundsTree. .closestPointToPoint closestPointToPoint( point:Vector3, target:Object={}, minThreshold:Number=0, maxThreshold:Number=Infinity ):target Computestheclosestdistancefromthepointtothemeshandgivesadditionalinformationintarget.Thetargetcanbeleftundefinedtodefaulttoanewobjectwhichisultimatelyreturnedbythefunction. IfapointisfoundthatiscloserthanminThresholdthenthefunctionwillreturnthatresultearly.AnytrianglesorpointsoutsideofmaxThresholdareignored.Ifnopointisfoundwithinthemin/maxthresholdsthennullisreturnedandthetargetobjectisnotmodified. target:{ point:Vector3, distance:Number, faceIndex:Number } ThereturnedfaceIndexcanbeusedwiththestandalonefunctiongetTriangleHitPointInfotoobtainmoreinformationlikeUVcoordinates,trianglenormalandmaterialIndex. .closestPointToGeometry closestPointToGeometry( geometry:BufferGeometry, geometryToBvh:Matrix4, target1:Object={}, target2:Object={}, minThreshold:Number=0, maxThreshold:Number=Infinity ):target1 Computestheclosestdistancefromthegeometrytothemeshandputstheclosestpointonthemeshintarget1(intheframeoftheBVH)andtheclosestpointontheothergeometryintarget2(inthegeometryframe).Iftarget1isnotprovidedanewObjectiscreatedandreturnedfromthefunction. ThegeometryToBvhparameteristhetransformofthegeometryintheBVH'slocalframe. IfapointisfoundthatiscloserthanminThresholdthenthefunctionwillreturnthatresultearly.AnytrianglesorpointsoutsideofmaxThresholdareignored.Ifnopointisfoundwithinthemin/maxthresholdsthennullisreturnedandthetargetobjectsarenotmodified. target1andtarget2areoptionalobjectsthatsimilartothetargetparameterinclosestPointPointandsetwiththesamefieldsasthatfunction. Thereturnedintarget1andtarget2canbeusedwiththestandalonefunctiongetTriangleHitPointInfotoobtainmoreinformationlikeUVcoordinates,trianglenormalandmaterialIndex. Notethatthisfunctioncanbeveryslowifgeometrydoesnothaveageometry.boundsTreecomputed. .shapecast shapecast( callbacks:{ traverseBoundsOrder:( box:Box3 )=>Number=null, intersectsBounds:( box:Box3, isLeaf:Boolean, score:Number|undefined, depth:Number, nodeIndex:Number )=>NOT_INTERSECTED|INTERSECTED|CONTAINED, intersectsRange:( triangleOffset:Number, triangleCount:Number contained:Boolean, depth:Number, nodeIndex:Number, box:Box3 )=>Boolean=null, intersectsTriangle:( triangle:ExtendedTriangle, triangleIndex:Number, contained:Boolean, depth:Number )=>Boolean=null, } ):Boolean Ageneralizedcastfunctionthatcanbeusedtoimplementintersectionlogicforcustomshapes.ThisisusedinternallyforintersectsBox,intersectsSphere,andmore.Thefunctionreturnsassoonasatrianglehasbeenreportedasintersectedandreturnstrueifatrianglehasbeenintersected.TheboundsaretraversedindepthfirstordercallingtraverseBoundsOrder,intersectsBoundsFunc,intersectsRange,andintersectsTriangleforeachnodeandusingtheresultstodeterminewhentoendtraversal.ThedepthvaluepassedtocallbacksindicatesthedepthoftheboundstheprovidedboxortrianglerangebelongstounlessthetrianglesareindicatedtobeCONTAINED,inwhichcasedepthisthedepthoftheparentboundsthatwerecontained.Thedepthfieldcanbeusedtoprecompute,cachetoanarray,andthenreadinformationaboutaparentboundtoimproveperformancewhiletraversingbecausenodesaretraversedinadpethfirstorder.ThetriangleIndexparameterspecifiestheindexofthetriangleintheindexbuffer.ThethreevertexindicescanbecomputedastriangleIndex*3+0,triangleIndex*3+1,triangleIndex*3+2. traverseBoundsOrdertakesasanargumenttheaxisalignedboundingboxrepresentinganinternalnodelocaltotheBVHandreturnsascore(oftendistance)usedtodeterminewhethertheleftorrightnodeshouldbetraversedfirst.Theshapewiththelowestscoreistraversedfirst. intersectsBoundstakestheaxisalignedboundingboxrepresentinganinternalnodelocaltothebvh,whetherornotthenodeisaleaf,thescorecalculatedbytraverseBoundsOrder,thenodedepth,andthenodeindex(forusewiththerefitfunction)andreturnsaconstantindicatingwhetherornottheboundsisintersectedorcontainedmeaningtraversalshouldcontinue.IfCONTAINEDisreturned(meaningtheboundsisentirelyencapsulatedbytheshape)thenanoptimizationistriggeredallowingtherangeand/ortriangleintersectioncallbackstoberunimmediatelyratherthantraversingtherestofthechildbounds. intersectsRangetakesatriangleoffsetandcountrepresentingthenumberoftrianglestobeiteratedover.1trianglefromthisrangerepresents3valuesinthegeometry'sindexbuffer.IfthisfunctionreturnstruethentraversalisstoppedandintersectsTriangleisnotcalledifprovided. intersectsTriangletakesatriangleandthetriangleindexandreturnswhetherornotthetrianglehasbeenintersected.Ifthetriangleisreportedtobeintersectedthetraversalendsandtheshapecastfunctioncompletes.Ifmultipletrianglesneedtobecollectedorintersectedreturnfalsehereandpushresultsontoanarray.containedissettotrueifoneoftheparentboundswasmarkedasentirelycontained(returnedCONTAINED)intheintersectsBoundsFuncfunction. .refit refit(nodeIndices:Array|Set=null):void Refitthenodeboundstothecurrenttrianglepositions.ThisisquickerthanregeneratinganewBVHbutwillnotbeoptimalaftersignificantchangestothevertices.nodeIndicesisasetofnodeindices(providedbytheshapecastfunction,seeexamplesnippetbelow)thatneedtoberefitincludingallinternalnodes.Ifoneofanodeschildrenisalsoincludedinthesetofnodeindicesthenonlytheincludedchildboundsaretraversed.IfneitherchildindexisincludedinthenodeIndicesset,though,thenitisassumedthateverychildbelowthatnodeneedstobeupdated. Here'showtogetthesetofindicesthatneedtoberefit: constnodeIndices=newSet(); bvh.shapecast( { intersectsBounds:(box,isLeaf,score,depth,nodeIndex)=>{ if(/*intersectsshape*/){ nodeIndices.add(nodeIndex); returnINTERSECTED; } returnNOT_INTERSECTED; }, intersectsRange:(offset,count,contained,depth,nodeIndex)=>{ /*collecttriangles/verticestomove*/ //thenodeIndexherewillhavealwaysalreadybeenaddedtothesetinthe //`intersectsBounds`callback. nodeIndices.add(nodeIndex); } } ); /*updatethepositionsofthetrianglevertices*/ //updatetheBVHboundsofjusttheboundsthatneedtobeupdated bvh.refit(nodeIndices); .getBoundingBox getBoundingBox(target:Box3):Box3 GettheboundingboxofthegeometrycomputedfromtherootnodeboundsoftheBVH.SignificantlyfasterthanBufferGeometry.computeBoundingBox. SerializedBVH .roots roots:Array .index index:TypedArray MeshBVHVisualizer extendsTHREE.Group Displaysaviewoftheboundstreeuptothegivendepthofthetree.Update()mustbecalledafteranyfieldsthataffectvisualizationgeometryarechanged. Note:Thevisualizerisexpectedtobeasiblingofthemeshbeingvisualized. .depth depth:Number Thedepthtotraverseandvisualizethetreeto. .color color=0x00FF88:THREE.Color Thecolortorendertheboundingvolumewith. .opacity opacity=0.3:Number Theopacitytorendertheboundingvolumewith. .displayParents displayParents=false:Boolean Whetherornottodisplaytheparentbounds. .displayEdges displayEdges=true:Boolean Iftruedisplaystheboundsasedgesotherdisplaystheboundsassolidmeshes. .edgeMaterial edgeMaterial:LineBasicMaterial Thematerialtousewhenrenderingedges. .meshMaterial meshMaterial:MeshBasicMaterial Thematerialtousewhenrenderingasasoldmeshes. .constructor constructor(mesh:THREE.Mesh,depth=10:Number) Instantiatesthehelperwithadepthandmeshtovisualize. .update update():void Updatesthedisplayoftheboundstreeinthecasethattheboundstreehaschangedorthedepthparameterhaschanged. .dispose dispose():void Disposesofthematerialused. ExtendedTriangle extendsTHREE.Triangle Anextendedversionofthree.js'Triangleclass.Avarietyofderivativevaluesarecachedontheobjecttoacceleratetheintersectionfunctions..needsUpdatemustbesettotruewhenmodifyingthetriangleparameters. .needsUpdate needsUpdate:Boolean Indicatesthatthetrianglefieldshavechangedsocachedvariablestoaccelerateotherfunctionexecutioncanbeupdated.Mustbesettotrueaftermodifyingthetrianglea,b,cfields. .intersectsTriangle intersectsTriangle(other:Triangle,target?:Line3):Boolean; Returnswhetherthetrianglesintersect.targetissettothelinesegmentrepresentingtheintersection. .intersectsSphere intersectsSphere(sphere:Sphere):Boolean Returnswhetherthetriangleintersectsthegivensphere. .closestPointToSegment closestPointToSegment(segment:Line3,target1?:Vector3,target2?:Vector3):Number Returnsthedistancetotheprovidedlinesegment.target1andtarget2aresettotheclosestpointsonthetriangleandsegmentrespectively. .distanceToPoint distanceToPoint(point:Vector3):Number Returnsthedistancetotheprovidedpoint. .distanceToTriangle distanceToTriangle(tri:Triangle):Number Returnsthedistancetotheprovidedtriangle. OrientedBox extendsTHREE.Box3 Anorientedversionofthree.js'Box3class.Avarietyofderivativevaluesarecachedontheobjecttoacceleratetheintersectionfunctions..needsUpdatemustbesettotruewhenmodifyingtheboxparameters. .matrix matrix:Matrix4 Matrixtransformationappliedtothebox. .needsUpdate updateUpdate:Boolean Indicatesthattheboundingboxfieldshavechangedsocachedvariablestoaccelerateotherfunctionexecutioncanbeupdated.Mustbesettotrueaftermodifyingtheorientedboxmin,max,matrixfields. .set set(min:Vector3,max:Vector3,matrix:Matrix4):this Setstheorientedboxparameters. .intersectsBox intersectsBox(box:Box3):Boolean Returnstrueifintersectingwiththeprovidedbox. .intersectsTriangle intersectsTriangle(tri:Triangle):Boolean Returnstrueifintersectingwiththeprovidedtriangle. .closestPointToPoint closestPointToPoint(point:Vector3,target=null:Vector3):Number Returnsthedistancetotheprovidedpoint.Setstargettotheclosestpointonthesurfaceoftheboxifprovided. .distanceToPoint distanceToPoint(point:Vector3):Number Returnsthedistancetotheprovidedpoint. .distanceToBox distanceToBox(box:Box3,threshold=0:Number,target1=null:Vector3,target2=null:Vector3):Number Returnsthedistancetotheprovidedbox.thresholdisanoptionaldistancetoreturnearlyifthedistanceisfoundtobewithinit.target1andtarget2aresettothepointsonthesurfaceofthisboxandtheboxargumentrespectively. Extensions Raycaster.firstHitOnly firstHitOnly=false:Boolean IftheRaycastermemberfirstHitOnlyissettotruethenthe.acceleratedRaycastfunctionwillcallthe.raycastFirstfunctiontoretrievehitswhichisgenerallyfaster. .computeBoundsTree computeBoundsTree(options:Object):void Apre-madeBufferGeometryextensionfunctionthatbuildsanewBVH,assignsittoboundsTree,andappliesthenewindexbuffertothegeometry.ComparabletocomputeBoundingBoxandcomputeBoundingSphere. THREE.BufferGeometry.prototype.computeBoundsTree=computeBoundsTree; .disposeBoundsTree disposeBoundsTree():void ABufferGeometryextensionfunctionthatdisposesoftheBVH. THREE.BufferGeometry.prototype.disposeBoundsTree=disposeBoundsTree; .acceleratedRaycast acceleratedRaycast(...) AnacceleratedraycastfunctionwiththesamesignatureasTHREE.Mesh.raycast.UsestheBVHforraycastingifit'savailableotherwiseitfallsbacktothebuilt-inapproach.TheresultsofthefunctionaredesignedtobeidenticaltotheresultsoftheconventionalTHREE.Mesh.raycastresults. IftheraycasterobjectbeingusedhasapropertyfirstHitOnlysettotrue,thentheraycastingwillterminateassoonasitfindstheclosestintersectiontotheray'soriginandreturnonlythatintersection.Thisistypicallyseveraltimesfasterthansearchingforallintersections. THREE.Mesh.prototype.raycast=acceleratedRaycast; StaticGeometryGenerator AutilityclassfortakingasetofSkinnedMeshesormorphtargetgeometryandbakingitintoasingle,staticgeometrythataBVHcanbegeneratedfor. .useGroups useGroups=true:Boolean Iftruethengroupsareusedtosupportanarrayofmaterialsonthemesh. .attributes attributes=['position','normal','tangent','uv','uv2']:Array Thesetofattributestocopyontothestaticgeometry. .applyWorldTransforms applyWorldTransforms=true:Boolean Whethertotransformtheverticesofthegeometrybytheworldtransformsofeachmeshwhengenerating. constructor constructor(object:Array) Takesanarrayofobjecthierarchiestobakeintoasinglestaticgeometry. .getMaterials getMaterials():Array Returnsanarrayofmaterialsforthemeshestobemerged.Thesecanbeusedalongsidethegeneratedgeometrywhencreatingamesh:newMesh(geometry,generator.getMaterials()). .generate generate(target=newBufferGeometry():BufferGeometry):BufferGeometry Generatesasingle,staticgeometryforthepassesmeshes.Whengeneratingforthefirsttimeanemptytargetgeometryisexpected.Thesamegeneratedgeometrycanbepassedintothefunctiononsubsequentcallstoupdatethegeometryinplacetosavememory.Anerrorwillbethrowniftheattributesorgeometryonthemeshestobakehasbeenchangedandareincompatiblelengths,types,etc. Onsubsequentcallsthe"index"bufferwillnotbemodifiedsoanyBVHgeneratedforthegeometryisunaffected.OncethegeometryisupdatedtheMeshBVH.refitfunctioncanbecalledtoupdatetheBVH. GenerateMeshBVHWorker HelperclassforgeneratingaMeshBVHforagivengeometryinasynchronouslyinaworker.ThegeometrypositionandindexbufferattributeArrayBuffersaretransferredtotheWorkerwhiletheBVHisbeinggeneratedmeaningthegeometrywillbeunavailabletousewhiletheBVHisbeingprocessedunlessSharedArrayBuffersareused.TheywillbeautomaticallyreplacedwhentheMeshBVHisfinishedgenerating. NOTEIt'sbesttoreuseasingleinstanceofthisclasstoavoidtheoverheadofinstantiatinganewWorker. SeenoteinAsyncronousGenerationusesnippet. .running running:Boolean; FlagindicatingwhetherornotaBVHisalreadybeinggeneratedintheworker. .generate generate(geometry:BufferGeometry,options:Object):Promise; GeneratesaMeshBVHinstanceforthegivengeometrywiththegivenoptionsinaWebWorker.ReturnsapromisethatresolveswiththegeneratedMeshBVH.Thisfunctionwillthrowanerrorifitisalreadyrunning. .dispose dispose():void; Terminatestheworker. DebugFunctions estimateMemoryInBytes estimateMemoryInBytes(bvh:MeshBVH):Number RoughlyestimatestheamountofmemoryinbytesaBVHisusing. getBVHExtremes getBVHExtremes(bvh:MeshBVH):Array Measurestheminandmaxextremesofthetreeincludingnodedepth,leaftrianglecount,andnumberofsplitsondifferentaxestoshowhowwellatreeisstructured.Returnsanarrayofextremesforeachgrouprootforthebvh.Theobjectsarestructuredlikeso: { //Thetotalnumberofnodesinthetreeincludingleafnodes. nodeCount:Number, //Thetotalnumberofleafnodesinthetree. leafNodeCount:Number, //Atotaltreescorebasedonthesurfaceareaheuristicscore //usefulforcomparingthequalityandperformancecapability //oftheboundstree.Lowerscoreisbetterandbasedonthesurface //areaofboundsandhowmanytrianglesarestoredwithin. surfaceAreaScore:Number, //Theminandmaxofleafnodesinthetree. depth:{min:Number,max:Number}, //Theminandmaxnumberoftrianglescontainedwithinthe //boundstheleafnodes. tris:{min:Number,max:Number}, //Thenumberofsplitsonanygivenaxis. splits:[Number,Number,Number] } NOTEThewhenusingtherefitfunctionthesurfaceAreaScorecanbeusedtocheckhowsignificantlythestructureoftheBVHhasdegradedandrebuilditifithaschangedbeyondsomethresholdratio. IndividualFunctions Functionsexportedindividuallynotpartofaclass. getTriangleHitPointInfo getTriangleHitPointInfo( point:Vector3, geometry:BufferGeometry, triangleIndex:Number target:Object ):Object Thisfunctionreturnsinformationofapointrelatedtoageometry.Itreturnsthetargetobjectoranewoneifpassedundefined: target:{ face:{ a:Number, b:Number, c:Number, materialIndex:Number, normal:Vector3 }, uv:Vector2 } a,b,c:Triangleindices materialIndex:Facematerialindexor0ifnotavailable. normal:Facenormal uv:UVcoordinates. ThisfunctioncanbeusedafteracalltoclosestPointPointorclosestPointToGeometrytoretrievemoredetailedresultinformation. ShaderandTexturePackingAPI InadditiontoqueriesinJavascripttheBVHcanbepackedintoaseriesoftexturessoraycastqueriescanbeperformedinashaderusingprovidedWebGLshaderfunctions.SeetheshaderimplementationinthesimpleGPUPathTracingexampleforanexampleonhowtousethefunctionality. *VertexAttributeTexture FloatVertexAttributeTexture UIntVertexAttributeTexture IntVertexAttributeTexture extendsTHREE.DataTexture Float,Uint,andIntVertexAttributeTextureimplementationsaredesignedtosimplifytheefficientpackingofathree.jsBufferAttributeintoatexture.Aninstancecanbetreatedasatextureandwhenpassingasauniformtoashadertheyshouldbeusedasasampler2d,usampler2d,andisampler2dwhenusingtheFloat,Uint,andInttexturetypesrespectively. .overrideItemSize overrideItemSize:Number=null TreatsBufferAttribute.itemSizeasthoughitweresettothisvaluewhenpackingthebufferattributetexture.ThrowsanerrorifthevaluedoesnotdivideevenlyintothelengthoftheBufferAttributebuffer(count*itemSize%overrideItemSize). SpecificallyusedtopackgeometryindicesintoanRGBtextureratherthananRedtexture. .updateFrom updateFrom(attribute:THREE.BufferAttribute):void UpdatesthetexturetohavethedatacontainedinthepassedBufferAttributeusingtheBufferAttributeitemSizefield,normalizedfield,andTypedArraylayouttodeterminetheappropriatetexturelayout,format,andtype.Thetexturedimensionswillalwaysbesquare.Becausetheseareintendedtobesampledas1Darraysthewidthofthetexturemsutbetakenintoaccounttoderiveasamplinguv.SeetexelFetch1DinshaderFunctions. MeshBVHUniformStruct AshaderuniformobjectcorrespondingtotheBVHshaderstructdefinedinshaderStructs.TheobjectcontainsfourtexturescontaininginformationabouttheBVHandgeometrysoitcanbequeriedinashaderusingthebvhintersectionfunctionsdefinedinshaderFunctions.ThisobjectisintendedtobeusedasashaderuniformandreadintheshaderasaBVHstruct. .updateFrom updateFrom(bvh:MeshBVH):void UpdatestheobjectandassociatedtextureswithdatafromtheprovidedBVH. .dispose dispose():void Disposeoftheassociatedtextures. ShaderFunctionandStructExports shaderStructs shaderStructs:string SetofshadersstructsanddefinedconstantsusedforinteractingwiththepackedBVHinashader.Seesrc/gpu/shaderFunctions.jsforfullimplementationsanddeclarations. shaderFunctions shaderFunctions:string SetofshaderfunctionsusedforinteractingwiththepackedBVHinashaderandsamplingVertexAttributeTextures.Seesrc/gpu/shaderFunctions.jsforfullimplementationsanddeclarations. Gotchas WhenqueryingtheMeshBVHdirectlyallshapesandgeometryareexpectedtobespecifiedinthelocalframeoftheBVH.Whenusingthree.js'builtinraycastingsystemallresultsareimplicitlytransformedintoworldcoordinates. Aboundstreecanbegeneratedforeitheranindexedornon-indexedBufferGeometry,butanindexwill beproducedandretainedasasideeffectoftheconstruction. Theboundshierarchyisnotdynamic,sogeometrythatusesmorphtargetsorskinningcannotbeused.Thoughifvertexpositionsaremodifieddirectlytherefitfunctioncanbeusedtoadjusttheboundstree. Ifthegeometryischangedthenanewboundstreewillneedtobegeneratedorrefit. InterleavedBufferAttributesarenotsupportedwiththegeometryindexbufferattribute. Aseparateboundstreeisgeneratedforeachgeometrygroup,whichcouldresultinlessthanoptimalraycastperformanceongeometrywithlotsofgroups. DuetoerrorsrelatedtofloatingpointprecisionitisrecommendedthatgeometrybecenteredusingBufferGeometry.center()beforecreatingtheBVHifthegeometryissufficientlylargeoroffcentersoboundstightlycontainthegeometryasmuchaspossible. UsedandSupportedby ...andmore! Keywordsgraphicsraycasttreeboundsthreejsthree-jsbounds-hierarchyperformanceraytracingpathtracinggeometrymeshdistanceintersectionaccelerationbvhwebvrwebxrInstallnpmithree-mesh-bvhRepositoryGitgithub.com/gkjohnson/three-mesh-bvhHomepagegithub.com/gkjohnson/three-mesh-bvh#readmeDownloadsWeeklyDownloads67,642Version0.5.12LicenseMITUnpackedSize1.14MBTotalFiles34Lastpublish6hoursagoCollaboratorsTryonRunKitReportmalware



請為這篇文章評分?