threepipe
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

pirms 2 gadiem
pirms 2 gadiem
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804
  1. # ThreePipe
  2. A new way to work with three.js, 3D models and rendering on the web.
  3. [ThreePipe](https://threepipe.org/) —
  4. [Github](https://github.com/repalash/threepipe) —
  5. [Examples](https://threepipe.org/examples/) —
  6. [API Reference](https://threepipe.org/docs/) —
  7. [WebGi](https://webgi.xyz/docs/)
  8. [![NPM Package](https://img.shields.io/npm/v/threepipe.svg)](https://www.npmjs.com/package/threepipe)
  9. [![Discord Server](https://img.shields.io/discord/956788102473584660?label=Discord&logo=discord)](https://discord.gg/apzU8rUWxY)
  10. [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://opensource.org/license/apache-2-0/)
  11. [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/repalash.svg?style=social&label=Follow%20%40repalash)](https://twitter.com/repalash)
  12. ThreePipe is a 3D framework built on top of [three.js](https://threejs.org/) in TypeScript with a focus on rendering quality, modularity, and extensibility.
  13. Key features include:
  14. - Simple, intuitive API for creating 3D model viewers/configurators/editors on web pages, with many built-in presets for common workflows and use-cases.
  15. - Companion [editor](https://threepipe.org/examples/tweakpane-editor/) to create, edit and configure 3D scenes in the browser.
  16. - Modular architecture that allows you to easily extend the viewer, scene objects, materials, shaders, rendering, post-processing and serialization with custom functionality.
  17. - Plugin system along with a rich library of built-in plugins that allows you to easily add new features to the viewer.
  18. - [uiconfig](https://github.com/repalash/uiconfig.js) compatibility to automatically generate configuration UIs in the browser.
  19. - Modular rendering pipeline with built-in deferred rendering, post-processing, RGBM HDR rendering, etc.
  20. - Material extension framework to modify/inject/build custom shader code into existing materials at runtime from plugins.
  21. - Extendable asset import, export and management pipeline with built-in support for gltf, glb, obj+mtl, fbx, materials(pmat/bmat), json, zip, png, jpeg, svg, webp, ktx2, ply, 3dm and many more.
  22. - Automatic serialization of all viewer and plugin settings in GLB(with custom extensions) and JSON formats.
  23. - Automatic disposal of all three.js resources with built-in reference management.
  24. ## Examples
  25. Code samples and demos covering various usecases and test are present in the [examples](./examples/) folder.
  26. Try them: https://threepipe.org/examples/
  27. View the source code by pressing the code button on the top left of the example page.
  28. To make changes and run the example, click on the CodePen button on the top right of the source code.
  29. ## Table of Contents
  30. - [ThreePipe](#threepipe)
  31. - [Examples](#examples)
  32. - [Table of Contents](#table-of-contents)
  33. - [Getting Started](#getting-started)
  34. - [HTML/JS Quickstart (CDN)](#htmljs-quickstart-cdn)
  35. - [NPM/YARN Package](#npmyarn)
  36. - [Installation](#installation)
  37. - [Loading a 3D Model](#loading-a-3d-model)
  38. - [License](#license)
  39. - [Status](#status)
  40. - [Documentation (API Reference)](#documentation)
  41. - [WebGi](#webgi)
  42. - [Contributing](#contributing)
  43. - [Features](#features)
  44. - [File Formats](#file-formats)
  45. - [Loading files](#loading-files)
  46. - [3D models](#3d-models)
  47. - [Materials](#materials)
  48. - [Images/Textures](#imagestextures)
  49. - [zip files](#zip-files)
  50. - [txt, json files](#txt-json-files)
  51. - [Data URLs](#data-urls)
  52. - [Local files, File and Blob](#local-files-file-and-blob)
  53. - [Background, Environment maps](#background-environment-maps)
  54. - [SVG strings](#svg-strings)
  55. - [Exporting files](#exporting-files)
  56. - [Exporting 3D models](#exporting-3d-models)
  57. - [Exporting Materials](#exporting-materials)
  58. - [Exporting Canvas Images](#exporting-canvas-images)
  59. - [Exporting Images/Textures](#exporting-imagestextures)
  60. - [Exporting Render Targets](#exporting-render-targets)
  61. - [Render Pipeline](#render-pipeline)
  62. - [Material Extension](#material-extension)
  63. - [UI Configuration](#ui-configuration)
  64. - [Serialization](#serialization)
  65. - [Plugin System](#plugin-system)
  66. - [Viewer API](#viewer-api)
  67. - [ThreeViewer](#threeviewer)
  68. - [RenderManager](#rendermanager)
  69. - [RootScene](#rootscene)
  70. - [ICamera](#icamera)
  71. - [AssetManager](#assetmanager)
  72. - [AssetImporter](#assetimporter)
  73. - [AssetExporter](#assetexporter)
  74. - [MaterialManager](#materialmanager)
  75. - [Plugins](#threepipe-plugins)
  76. - [TonemapPlugin](#tonemapplugin) - Add tonemap to the final screen pass
  77. - [DropzonePlugin](#dropzoneplugin) - Drag and drop local files to import and load
  78. - [ProgressivePlugin](#progressiveplugin) - Post-render pass to blend the last frame with the current frame
  79. - [DepthBufferPlugin](#depthbufferplugin) - Pre-rendering of depth buffer
  80. - [NormalBufferPlugin](#normalbufferplugin) - Pre-rendering of normal buffer
  81. - [GBufferPlugin](#depthnormalbufferplugin) - Pre-rendering of depth and normal buffers in a single pass buffer
  82. - [PickingPlugin](#pickingplugin) - Adds support for selecting objects in the viewer with user interactions and selection widgets
  83. - [GLTFAnimationPlugin](#gltfanimationplugin) - Add support for playing and seeking gltf animations
  84. - [PopmotionPlugin](#popmotionplugin) - Integrates with popmotion.io library for animation/tweening
  85. - [CameraViewPlugin](#cameraviewplugin) - Add support for saving, loading, animating, looping between camera views
  86. - [RenderTargetPreviewPlugin](#rendertargetpreviewplugin) - Preview any render target in a UI panel over the canvas
  87. - [GeometryUVPreviewPlugin](#geometryuvpreviewplugin) - Preview UVs of any geometry in a UI panel over the canvas
  88. - [FrameFadePlugin](#framefadeplugin) - Post-render pass to smoothly fade to a new rendered frame over time
  89. - [VignettePlugin](#vignetteplugin) - Add Vignette effect by patching the final screen pass
  90. - [ChromaticAberrationPlugin](#chromaticaberrationplugin) - Add Chromatic Aberration effect by patching the final screen pass
  91. - [FilmicGrainPlugin](#filmicgrainplugin) - Add Filmic Grain effect by patching the final screen pass
  92. - [HDRiGroundPlugin](#hdrigroundplugin) - Add support for ground projected hdri/skybox to the webgl background shader.
  93. - [Rhino3dmLoadPlugin](#rhino3dmloadplugin) - Add support for loading .3dm files
  94. - [PLYLoadPlugin](#plyloadplugin) - Add support for loading .ply files
  95. - [STLLoadPlugin](#stlloadplugin) - Add support for loading .stl files
  96. - [KTX2LoadPlugin](#ktx2loadplugin) - Add support for loading .ktx2 files
  97. - [KTXLoadPlugin](#ktxloadplugin) - Add support for loading .ktx files
  98. - [Packages](#threepipe-packages)
  99. - [@threepipe/plugin-tweakpane](#threepipeplugin-tweakpane) Tweakpane UI Plugin
  100. - [@threepipe/plugin-tweakpane-editor](#threepipeplugin-tweakpane-editor) - Tweakpane Editor Plugin
  101. - [@threepipe/plugin-extra-importers](#threepipeplugin-extra-importers) - Plugin for loading more file types supported by loaders in three.js
  102. - [@threepipe/plugin-blend-importer](#threepipeplugin-blend-importer) - Blender to add support for loading .blend file
  103. ## Getting Started
  104. ### HTML/JS Quickstart (CDN)
  105. ```html
  106. <canvas id="three-canvas" style="width: 800px; height: 600px;"></canvas>
  107. <script type="module">
  108. import {ThreeViewer, DepthBufferPlugin} from 'https://threepipe.org/dist/index.mjs'
  109. const viewer = new ThreeViewer({canvas: document.getElementById('three-canvas')})
  110. // Add some plugins
  111. viewer.addPluginSync(new DepthBufferPlugin())
  112. // Load an environment map
  113. const envPromise = viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  114. const modelPromise = viewer.load('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  115. autoCenter: true,
  116. autoScale: true,
  117. })
  118. Promise.all([envPromise, modelPromise]).then(([env, model]) => {
  119. console.log('Loaded', model, env, viewer)
  120. })
  121. </script>
  122. ```
  123. Check it in action: https://threepipe.org/examples/#html-sample/
  124. Check out the details about the [ThreeViewer API](#viewer-api) and more [plugins](#threepipe-plugins) below.
  125. ### NPM/YARN
  126. ### Installation
  127. ```bash
  128. npm install threepipe
  129. ```
  130. ### Loading a 3D Model
  131. First, create a canvas element in your HTML page:
  132. ```html
  133. <canvas id="three-canvas" style="width: 800px; height: 600px;"></canvas>
  134. ```
  135. Then, import the viewer and create a new instance:
  136. ```typescript
  137. import {ThreeViewer, IObject3D} from 'threepipe'
  138. // Create a viewer
  139. const viewer = new ThreeViewer({canvas: document.getElementById('three-canvas') as HTMLCanvasElement})
  140. // Load an environment map
  141. await viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  142. // Load a model
  143. const result = await viewer.load<IObject3D>('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  144. autoCenter: true,
  145. autoScale: true,
  146. })
  147. ```
  148. That's it! You should now see a 3D model on your page.
  149. The 3D model can be opened in the [editor](TODO) to view and edit the scene settings, objects, materials, lights, cameras, post-processing, etc. and exported as a GLB file. All settings are automatically serialized and saved in the GLB file, which can be loaded into the viewer. Any plugins used in the editor can be added to the viewer to add the same functionality. The plugin data is automatically loaded(if the plugin is added) when the model is added to the scene.
  150. The viewer initializes with a Scene, Camera, Camera controls(Orbit Controls), several importers, exporters and a default rendering pipeline. Additional functionality can be added with plugins.
  151. Check out the GLTF Load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#gltf-load/
  152. Check out the [Plugins](#plugins) section below to learn how to add additional functionality to the viewer.
  153. ## License
  154. The core framework([src](https://github.com/repalash/threepipe/tree/master/src), [dist](https://github.com/repalash/threepipe/tree/master/dist), [examples](https://github.com/repalash/threepipe/tree/master/examples) folders) and any [plugins](https://github.com/repalash/threepipe/tree/master/plugins) without a separate license are under the Free [Apache 2.0 license](https://github.com/repalash/threepipe/tree/master/LICENSE).
  155. Some plugins(in the [plugins](https://github.com/repalash/threepipe/tree/master/plugins) folder) might have different licenses. Check the individual plugin documentation and the source folder/files for more details.
  156. ## Status
  157. The project is in `alpha` stage and under active development. Many features will be added but the core API will not change significantly in future releases.
  158. Check out [WebGi](https://webgi.xyz/) for an advanced tailor-made solution for e-commerce, jewelry, automobile, apparel, furniture etc.
  159. ## Documentation
  160. Check the list of all functions, classes and types in the [API Reference Docs](https://threepipe.org/docs/).
  161. ## WebGi
  162. Check out WebGi - Premium Photo-realistic 3D rendering framework and tools for web applications and online commerce along with custom modules and rendering solutions for e-commerce, jewelry, automobile, apparel, furniture and other retail applications.
  163. [Homepage](https://webgi.xyz/) &mdash; [Docs](https://webgi.xyz/docs/)
  164. [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/repalash.svg?style=social&label=Follow%20%40pixotronics)](https://twitter.com/pixotronics)
  165. ## Contributing
  166. Contributions to ThreePipe are welcome and encouraged! Feel free to open issues and pull requests on the GitHub repository.
  167. # Features
  168. ## File Formats
  169. ThreePipe Asset Manager supports the import of the following file formats out of the box:
  170. * **Models**: gltf, glb, obj+mtl, fbx, drc
  171. * **Materials**: mat, pmat, bmat (json based), registered material template slugs
  172. * **Images**: webp, png, jpeg, jpg, svg, ico, avif, hdr, exr
  173. * **Misc**: json, vjson, zip, txt
  174. Plugins can add additional formats:
  175. * Models
  176. * 3dm - Using [Rhino3dmLoadPlugin](#Rhino3dmLoadPlugin)
  177. * ply - Using [PLYLoadPlugin](#PLYLoadPlugin)
  178. * usdz - Using [USDZLoadPlugin](#USDZLoadPlugin)
  179. * stl - Using [STLLoadPlugin](#STLLoadPlugin)
  180. * ktx - Using [KTXLoadPlugin](#KTXLoadPlugin)
  181. * ktx2 - Using [KTX2LoadPlugin](#KTX2LoadPlugin)
  182. Plugins to support more model formats are available in the package [@threepipe/plugin-extra-importers](#threepipeplugin-extra-importers) including .3ds,
  183. .3mf, .collada, .amf, .bvh, .vox, .gcode, .mdd, .pcd, .tilt, .wrl, .mpd, .vtk, .xyz
  184. ## Loading files
  185. ThreePipe uses the [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) to load files.
  186. The AssetManager has support for loading files from URLs, local files and data URLs.
  187. The AssetManager also adds support for loading files from a zip archive. The zip files are automatically unzipped, and the files are loaded from the zip archive.
  188. [viewer.load()](https://threepipe.org/docs/classes/ThreeViewer.html#load) is a high-level wrapper for loading files from the AssetManager.
  189. It automatically adds the loaded object to the scene and returns a promise that resolves to the loaded object,
  190. the materials are also automatically registered to the material manager.
  191. AssetManager internally uses [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html),
  192. which provides a low-level API
  193. for managing three.js [LoadingManager](https://threejs.org/docs/#api/en/loaders/LoadingManager)
  194. and adding and registering loaders for different file types.
  195. If the purpose is not to add files to the scene then [viewer.assetManager.importer.import()](https://threepipe.org/docs/classes/AssetImporter.html#import) method can be used
  196. to import files from the `AssetImporter`.
  197. viewer.assetManager.loadImported()](https://threepipe.org/docs/classes/AssetManager.html#loadImported)
  198. can then be called to load the imported files after any processing.
  199. The `viewer.load()`, `viewer.assetManager.addAsset()`
  200. and `viewer.assetManager.addAssetSingle()` methods perform combination of `import` and `loadImported`.
  201. ### 3D models
  202. The 3d models are added to `viewer.scene.modelRoot` on `viewer.load` unless some option is specified.
  203. ```typescript
  204. const objectGlb = await viewer.load<IObject3D>('https://example.com/file.glb')
  205. const objectFbx = await viewer.load<IObject3D>('https://example.com/file.fbx')
  206. const objectObj = await viewer.load<IObject3D>('https://example.com/file.obj') // .mtl referenced in obj is automatically loaded
  207. // ... load any 3d model file as an object
  208. ```
  209. Here, we are casting to [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) type
  210. to get the proper type and autocomplete for the object.
  211. `IObject3D` inherits [Object3D](https://threejs.org/docs/#api/en/core/Object3D) from three.js and adds some additional properties.
  212. For JavaScript, the type can be omitted.
  213. ```javascript
  214. const objectGlb = await viewer.load('https://example.com/file.glb')
  215. ```
  216. When loading models, several options can be passed to automatically process the model first time, like `autoScale`, `autoCenter`, `addToRoot` etc. Check [AddObjectOptions](https://threepipe.org/docs/interfaces/AddObjectOptions.html) and [ImportAddOptions](https://threepipe.org/docs/interfaces/ImportAddOptions.html) for more details.
  217. ### Materials
  218. The materials downloaded as PMAT/BMAT/JSON etc from threepipe,
  219. webgi or the editor can be loaded
  220. and registered with the [MaterialManager](https://threepipe.org/docs/classes/MaterialManager)
  221. using the `viewer.load` method.
  222. Custom material types can also be registered by plugins(like dmat for diamonds), which can also be loaded automatically using the `viewer.load` method.
  223. ```typescript
  224. const pMaterial = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  225. const bMaterial = await viewer.load<UnlitMaterial>('https://example.com/file.bmat')
  226. // ... load any material file as a material
  227. ```
  228. Casting to [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial) or [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial) is optional but recommended to get the proper type and autocomplete for the material.
  229. To assign the material on any object, set it to `object.material`
  230. ```typescript
  231. // find a loaded mesh in the scene
  232. const object = viewer.scene.getObjectByName('objectName');
  233. // assign the material
  234. object.material = pMaterial;
  235. ```
  236. To copy the properties without changing the material reference, use `material.copy()` or `material.setValues()` methods.
  237. ```typescript
  238. object.material.copy(pMaterial);
  239. // or use material manager to apply to multiple materials.
  240. viewer.assetManager.materialManager.applyMaterial(pMaterial, 'METAL') // apply props to all materials/objects with the name METAL
  241. ```
  242. TODO: add examples for material load and copy
  243. ### Images/Textures
  244. Images can be loaded using the `viewer.load` method.
  245. There is built-in support for loading all image formats supported by the browser (webp, png, jpeg, jpg, svg, ico, avif) and hdr, exr, hdr.png formats for all browsers.
  246. More formats like ktx2, ktx, etc. can be added using plugins.
  247. ```typescript
  248. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  249. // ... load any image file as a texture
  250. ```
  251. Casting to [ITexture](https://threepipe.org/docs/interfaces/ITexture.html) is optional
  252. but recommended to get the proper type and autocomplete for the texture.
  253. It inherits from three.js [Texture](https://threejs.org/docs/#api/en/textures/Texture) and adds some additional properties.
  254. To assign the texture on any material, set it to `material.map`
  255. ```typescript
  256. // find a loaded mesh in the scene
  257. const object = viewer.scene.getObjectByName('objectName');
  258. const material = object.material as PhysicalMaterial;
  259. // assign the texture
  260. material.map = texture;
  261. material.setDirty() // to let the viewer know that the material has changed and needs to re-render the scene. This will also trigger fade effect if FrameFadePlugin is added.
  262. ```
  263. Check out the image load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#image-load/
  264. ### Zip files
  265. .zip files are automatically unzipped and the files are sent to re-load recursively when loaded with `viewer.load`.
  266. Any level of zip hierarchy is flattened.
  267. Loading files like .gltf with references to assets inside the zip file,
  268. any relative references are also automatically resolved.
  269. This is supported for file types like gltf, glb, obj,
  270. etc which support references to external files and has `root` set to `true in [IImporter](https://threepipe.org/docs/interfaces/IImporter.html).
  271. ```typescript
  272. const objectGltf = await viewer.load<IObject3D>('https://example.com/model.gltf.zip')
  273. ```
  274. If we know that the zip file contains a single gltf with all the assets, we can cast the result to [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) type.
  275. To load multiple assets from zip files like multiple textures or materials, use `viewer.assetManager.addAsset` method which returns a promise of array of loaded assets.
  276. ```typescript
  277. const textures = await viewer.assetManager.addAsset<ITexture[]>('https://example.com/textures.zip')
  278. const materials = await viewer.assetManager.addAsset<IMaterial[]>('https://example.com/materials.zip')
  279. ```
  280. The auto import of zip contents can be disabled to get the files and blobs in the zip
  281. ```typescript
  282. const zip = await viewer.load<any>('https://example.com/file.zip', {autoImportZipContents: false})
  283. ```
  284. TODO - add example for loading zip files.
  285. ### txt, json files
  286. Text and JSON files can be loaded using the `viewer.load` method and return strings and objects respectively.
  287. ```typescript
  288. const text = await viewer.load<string>('https://example.com/file.txt')
  289. const json = await viewer.load<any>('https://example.com/file.json')
  290. ```
  291. ### Data URLs
  292. Data URLs can be loaded using the `viewer.load` method. The correct mime-type is required to be set in the data URL for finding the correct importer.
  293. ```typescript
  294. const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' // ... some data url
  295. const texture = await viewer.load<ITexture>(dataUrl)
  296. ```
  297. ### Local files, File and Blob
  298. Local files can be loaded using the `viewer.load` method by passing a [IAsset](https://threepipe.org/docs/interfaces/IAsset) object with [File](https://developer.mozilla.org/en-US/docs/Web/API/File) or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object.
  299. ```typescript
  300. const file: File|Blob = fileObject // create a new file, blob or get from input element
  301. const text = await viewer.load<IObject>({
  302. // a path/name is required to determine the proper importer by extension. `file.name` can also be used if available
  303. path: 'file.glb',
  304. file
  305. })
  306. ```
  307. The same can be done for any file type.
  308. To load a `Map` of files(like when multiple files are dragged and dropped on the webpage) with internal references to other files, use `viewer.assetManager.importer.importFiles` method. Check the source for [DropzonePlugin](#dropzoneplugin) for an example.
  309. ### Background, Environment maps
  310. The background and environment maps can be set using the `viewer.setBackgroundMap` and `viewer.setEnvironmentMap` methods respectively. These accept both loaded textures from `viewer.load` and direct URLs. Files can be of any image format including hdr, exr.
  311. ```typescript
  312. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  313. await viewer.setBackgroundMap('https://example.com/file.png')
  314. ```
  315. The same texture can be set to both by setting `setBackground` or `setEnvironment` to true in the options:
  316. ```typescript
  317. await viewer.setEnvironmentMap('https://example.com/file.hdr', {setBackground: true})
  318. ```
  319. Check the HDR Load example to see it in action: https://threepipe.org/examples/#hdr-load/
  320. ### SVG strings
  321. SVG strings can be converted to data urls using the [svgUrl](https://repalash.com/ts-browser-helpers/functions/svgUrl.html) string template function
  322. ```typescript
  323. const svgDataUrl = svgUrl`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> ... </svg>`;
  324. const texture = await viewer.load<ITexture>(dataUrl)
  325. ```
  326. ### Custom file types
  327. Custom file importers/loaders can be registered to the `AssetImporter` using the `addImporter` method.
  328. ```typescript
  329. class CustomLoader extends FileLoader implements ILoader{
  330. constructor(manager?: LoadingManager) {
  331. super(manager);
  332. }
  333. load(url: string, onLoad: (data: any) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Mesh {
  334. this.setResponseType('json')
  335. return super.load(url, (json: any)=>{
  336. const mat = new PhysicalMaterial(json)
  337. onLoad?.(mat)
  338. }, onProgress, onError)
  339. }
  340. }
  341. viewer.assetManager.importer.addImporter(new Importer(CustomLoader, ['ext'], ['mime/type'], false))
  342. // load the file
  343. const mat = await viewer.load<PhysicalMaterial>('https://example.com/file.ext')
  344. ```
  345. ## Exporting files
  346. Threepipe has support for exporting various asset type with AssetManager,
  347. as well as support to export viewer and plugin configuration, arbitrary objects etc using the [serialization](#serialization) system.
  348. [viewer.export()](https://threepipe.org/docs/classes/ThreeViewer.html#export) is a high-level wrapper for exporting scene objects, materials, textures, render targets, viewer/scene configuration and plugin configurations.
  349. AssetManager internally uses [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html) to export files.
  350. AssetExporter includes some basic exporters for glb, exr, textures,
  351. and materials and a system to register exporters for different file types with plugins or custom exporters.
  352. ### Exporting 3D models
  353. Export the root scene as glb
  354. ```typescript
  355. const blob = await viewer.exportScene({
  356. viewerConfig: true, // default = true. export all viewer and plugin configuration. if false only the model root object is exported.
  357. })
  358. // download the file
  359. downloadBlob(blob, 'scene.glb')
  360. ```
  361. Export a single object from the scene as glb
  362. ```typescript
  363. const object = viewer.scene.getObjectByName('objectName');
  364. const glb: Blob = await viewer.export(object, {
  365. exportExt: 'glb', // default = glb for models
  366. embedUrlImages: true, // default = false. embed images in glb even when url is available.
  367. })
  368. // download the file
  369. downloadBlob(glb, 'object.glb')
  370. ```
  371. Check the example [glb-export](https://threepipe.org/examples/#glb-export/) to see a demo.
  372. ### Exporting Materials
  373. Export a material
  374. ```typescript
  375. const material = viewer.assetManager.materialManager.findMaterialsByName('materialName')[0];
  376. // or
  377. // const material = viewer.scene.getObjectByName('objectName').material;
  378. const blob = await viewer.export(material)
  379. // download the file
  380. downloadBlob(blob, 'material.' + blob.ext)
  381. ```
  382. Check the example [pmat-material-export](https://threepipe.org/examples/#pmat-material-export/) to see a demo.
  383. ### Exporting Canvas Images
  384. Canvas Screenshot/snapshot can be exported as png, jpeg or webp(if supported by the browser)
  385. ```typescript
  386. const blob = await viewer.getScreenshotBlob({mimeType: 'image/' + type, quality: 0.85})
  387. // or to get data url:
  388. // const dataUrl = await viewer.getScreenshotDataUrl({mimeType: 'image/' + type, quality: 0.85})
  389. // download the file
  390. downloadBlob(blob, 'screenshot.' + blob.ext)
  391. ```
  392. Check the example [image-snapshot-export](https://threepipe.org/examples/#image-snapshot-export/) to see a demo.
  393. ### Exporting Textures
  394. Textures can be exported to JSON using `viewer.export` or `AssetExporter`
  395. ```typescript
  396. const texture = await viewer.load('https://example.com/file.jpeg')
  397. const blob = await viewer.export(texture)
  398. downloadBlob(blob, texture.name + '.' + blob.ext)
  399. ```
  400. Render target textures can be exported with `viewer.renderManager.exportRenderTarget` or `viewer.export`,
  401. read about [Exporting Render Targets](#exporting-render-targets) below.
  402. TODO: add examples for texture export
  403. Textures and Uint8 Data Textures can be exported as a data url or copied to a new canvas
  404. ```typescript
  405. // get a base64 data url
  406. const dataUrl = textureToDataUrl(texture, 4096, false, 'image/png') // texture or data texture, max-size, flipY, mimeType
  407. // or copy to a new canvas
  408. const canvas = textureToCanvas(texture, 4096) // texture or data texture, max-size
  409. ```
  410. Data Textures of type Half float and Float can be exported with `viewer.export`
  411. ```typescript
  412. const dataTex = await viewer.load('https://example.com/file.hdr')
  413. const blob = await viewer.export(dataTexture, {exportExt: 'exr'})
  414. ```
  415. Check the example [hdr-to-exr](https://threepipe.org/examples/#hdr-to-exr/) to see a demo of HDR to EXR conversion.
  416. TODO: add support to export unsigned byte textures as png, jpeg, webp
  417. ### Exporting Images
  418. Exporting Textures as Images with image of types ImageBitmap, HTMLImageElement,
  419. HTMLOrSVGImageElement, CanvasImageSource, HTMLCanvasElement,
  420. OffscreenCanvas can be exported to png data urls with [imageBitmapToBase64](https://repalash.com/ts-browser-helpers/functions/imageBitmapToBase64.html) function.
  421. ```typescript
  422. const texture = await viewer.load('https://example.com/file.jpeg')
  423. const dataUrl = await imageBitmapToBase64(texture.image, 'image/png', 0.85);
  424. ```
  425. TODO: add support for texture export as images in AssetExporter
  426. ### Exporting Render Targets
  427. Unsigned byte render targets can be exported as png, jpeg or webp(if supported by the browser)
  428. ```typescript
  429. const depthPlugin = viewer.addPluginSync(DepthBufferPlugin, UnsignedByteType)
  430. // wait for the first render
  431. const blob = await viewer.export(depthPlugin.target!, {exportExt: 'png'})
  432. if (blob) downloadBlob(blob, target.texture.name + '.' + blob.ext)
  433. ```
  434. Half float and float render targets can be exported as exr
  435. ```typescript
  436. const depthPlugin = viewer.addPluginSync(DepthBufferPlugin, HalfFloatType)
  437. // wait for the first render
  438. const blob = await viewer.export(depthPlugin.target!, {exportExt: 'exr'})
  439. if (blob) downloadBlob(blob, target.texture.name + '.' + blob.ext)
  440. ```
  441. Note: `exportExt` is determined automatically if not specified.
  442. ## Render pipeline
  443. Threepipe includes a [RenderManager](https://threepipe.org/docs/classes/RenderManager.html) for managing the composition pipeline, and provides helpers for rendering and render target management.
  444. The RenderManager includes a [EffectComposer](https://threejs.org/docs/#api/en/postprocessing/EffectComposer) from three.js for rendering passes and a [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) for rendering,
  445. but the pass management and sorting is managed by the RenderManager itself.
  446. The RenderManager inherits from [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html)
  447. which provides utilities for creating, tracking and destroying dedicated and temporary render targets.
  448. ### Render Targets
  449. Render targets can be created
  450. using the `viewer.renderManager.createTarget` and `viewer.renderManager.createTargetCustom` methods.
  451. These can then be disposed using the `viewer.renderManager.disposeTarget` method when not needed anymore.
  452. Or to create temp targets for one time use `viewer.renderManager.getTempTarget` and `viewer.renderManager.releaseTempTarget` methods.
  453. can be used.
  454. All created render targets are tracked in the RenderManager,
  455. and are resized and disposed automatically when needed along with the viewer.
  456. ```typescript
  457. const newTarget = viewer.renderManager.createTarget({sizeMultiplier: 1})
  458. // or
  459. const newTarget2 = viewer.renderManager.createTarget({size: {
  460. width: 1024,
  461. height: 1024,
  462. },
  463. type: HalfFloatType
  464. })
  465. // or clone an existing target
  466. const newTarget3 = viewer.renderManager.composerTarget.clone()
  467. // for multi-sample render target
  468. const newTarget4 = viewer.renderManager.createTarget({sizeMultiplier: 1, samples: 4})
  469. // or create a custom target
  470. const newTarget5 = viewer.renderManager.createTargetCustom(
  471. {width: 1024, height: 1024},
  472. {type: HalfFloatType},
  473. WebGLCubeRenderTarget
  474. )
  475. // dispose targets
  476. viewer.renderManager.disposeTarget(newTarget)
  477. viewer.renderManager.disposeTarget(newTarget2)
  478. viewer.renderManager.disposeTarget(newTarget3)
  479. viewer.renderManager.disposeTarget(newTarget4)
  480. viewer.renderManager.disposeTarget(newTarget5)
  481. // get a temporary target
  482. const tempTarget = viewer.renderManager.getTempTarget({sizeMultiplier: 1})
  483. // release the temporary target
  484. viewer.renderManager.releaseTempTarget(tempTarget)
  485. ```
  486. Note: Render targets created with a sizeMultiplier are automatically resized when the canvas is resized.
  487. ### Passes
  488. By default, the render pipeline includes 2 passes -
  489. [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) for rendering the scene hierarchy and [ScreenPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass)
  490. for rendering the final output on the canvas.
  491. More passes can be added and removed from the pipeline
  492. using the [registerPass](https://threepipe.org/docs/classes/RenderManager.html#registerPass) and [unregisterPass](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) methods.
  493. The pipeline passes need
  494. to follow the interface of [IPipelinePass](https://threepipe.org/docs/interfaces/IPipelinePass.html) and [IPipelinePassPlugin](https://threepipe.org/docs/interfaces/IPipelinePassPlugin.html).
  495. Which adds some important parameters over the three.js Pass,
  496. like pass id and support for defining where the pass should be added in the pipeline and it's dependants.
  497. ```typescript
  498. const pass = new GBufferRenderPass('customPass', viewer.renderManager.createTarget({sizeMultiplier: 1}))
  499. pass.before = ['render'] // Add the pass before the render pass
  500. pass.after = [] // Add the pass after these passes (none in this case)
  501. pass.required = ['render'] // render pass is required to be in the pipeline for this
  502. viewer.renderManager.registerPass(pass)
  503. ```
  504. Note:
  505. See [PipelinePassPlugin](https://threepipe.org/docs/classes/PipelinePassPlugin.html) for an abstract plugin
  506. that provides the boilerplate to create a plugin that registers a custom pass in the pipeline.
  507. Check [NormalBufferPlugin](https://threepipe.org/docs/classes/NormalBufferPlugin.html) for an example of that.
  508. Note: All effects in post-processing or material extension need not be a separate pass in the pipeline.
  509. Most effects can be achieved with either extending the scene object material shaders or the Screen Pass material shader
  510. using [Material extension](#material-extension) system
  511. ## Material Extension
  512. Threepipe includes a Material extension system along with a material manager.
  513. The material manager is used to register materials and material extensions.
  514. The material extensions are used to extend any material in the scene,
  515. or any plugin/pass with additional uniforms, defines, shader snippets and provides hooks.
  516. The material extensions are automatically applied to all materials in the scene that are compatible,
  517. when the extension is registered or when the material is added to the scene.
  518. Threepipe includes several built-in materials like
  519. [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial.html),
  520. [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial.html),
  521. [ExtendedShaderMaterial](https://threepipe.org/docs/classes/ExtendedShaderMaterial.html), [LegacyPhongMaterial](https://threepipe.org/docs/classes/LegacyPhongMaterial.html),
  522. that include support for extending the material.
  523. Any three.js material can be made extendable,
  524. check the `ShaderPass2` class for a simple example that adds support for material extension to three.js ShaderPass.
  525. The material extensions must follow the [MaterialExtension](https://threepipe.org/docs/interfaces/MaterialExtension.html) interface.
  526. Many plugins create their own material extensions either for the scene materials or shader passes(like the screen pass).
  527. Some plugins like `DepthBufferPlugin` also provides helper material extensions for other custom plugins
  528. to fetch value in the depth buffer.
  529. A sample material extension
  530. ```typescript
  531. const extension: MaterialExtension = {
  532. shaderExtender: (shader)=> {
  533. // change the shader properties like shader.fragmentShader, etc
  534. },
  535. parsFragmentSnippet: ` // add some code before the main function in the fragment shader
  536. uniform sampler2D tTexture;
  537. uniform float opacity;
  538. `,
  539. extraUniforms: {
  540. tTexture: ()=>({value: getTexture()}),
  541. opacity: {value: 1}
  542. // add additional uniforms, these can be IUniform or functions that return IUniform
  543. },
  544. extraDefines: {
  545. ['DEPTH_PACKING']: BasicDepthPacking,
  546. ['SOME_DEFINE']: ()=>"1",
  547. // add additional defines, these can be values or functions that return values
  548. },
  549. priority: 100, // priority when using multiple extensions on the same material
  550. isCompatible: (material) => material.isMeshBasicMaterial, // check if the material is compatible with this extension,
  551. computeCacheKey: (material) => material.uuid, // a custom cache key for the material extension. Shader is recompiled when this is changed
  552. onObjectRender: (object: Object3D, material: IMaterial) => {
  553. // called when some object is rendererd which has a material with this extension.
  554. },
  555. // uiConfig
  556. // check more properties and hooks in the MaterialExtension interface
  557. }
  558. // The extension can be registered to all the materials using the MaterialManager
  559. viewer.assetManager.materialManager.registerMaterialExtension(extension)
  560. // or register it on a single material (like the Screen Pass)
  561. viewer.renderManager.screenPass.material.registerMaterialExtensions([extension])
  562. ```
  563. ## UI Configuration
  564. Most of the classes and plugins in Threepipe include [uiconfig.js](https://repalash.com/uiconfig.js/) support
  565. and can be used to create configuration UIs, 3d configurators and even full-editors.
  566. The UIs are automatically generated based on the configuration object under `.uiConfig` property on all objects.
  567. These are of type [UiObjectConfig](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html).
  568. In some classes, the ui configs are also generated using typescript decorators.
  569. The `uiConfig` is also added to all three.js objects and materials when they are added to the scene.
  570. The UIs can be generated at runtime using any of the UI plugins like [TweakpaneUIPlugin](#threepipeplugin-tweakpane).
  571. An example showing how to create a UI for a material
  572. ```typescript
  573. const ui = viewer.addPluginSync(TweakpaneUiPlugin)
  574. const object = viewer.scene.getObjectByName('objectName');
  575. const material = object.material as PhysicalMaterial;
  576. ui.appendChild(material.uiConfig)
  577. ```
  578. See it in action: https://threepipe.org/examples/#material-uiconfig/
  579. Check more examples showing [Viewer UI](https://threepipe.org/examples/#viewer-uiconfig/),
  580. [Scene UI](https://threepipe.org/examples/#scene-uiconfig/),
  581. [Object UI](https://threepipe.org/examples/#object-uiconfig/), [Camera UI](https://threepipe.org/examples/#camera-uiconfig/)
  582. [TweakpaneEditorPlugin](#threepipeplugin-tweakpane-editor) further uses the Tweakpane configuration panel along with various plugins to create an 3d editor.
  583. Custom UI configuration can be created to generate custom UI for the editor or tweaking.
  584. This can be done by using typescript decorators or defining the UI in javascript as a [UiObjectConfig](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html) object.
  585. Here is a sample of extending the orbit controls class with decorators to automatically generate UI.
  586. ```typescript
  587. @uiPanelContainer('Orbit Controls')
  588. export class OrbitControlsWithUi extends OrbitControls implements IUiConfigContainer {
  589. // for autocomplete
  590. uiConfig?: UiObjectConfig<void, 'panel'>
  591. @uiToggle() enabled = true
  592. @uiToggle() dollyZoom = false
  593. @uiToggle() enableDamping = true
  594. @uiInput() dampingFactor = 0.08
  595. @uiToggle() autoRotate = false
  596. @uiInput() autoRotateSpeed = 2.0
  597. @uiToggle() enableZoom = true
  598. @uiInput() zoomSpeed = 0.15
  599. @uiInput() maxZoomSpeed = 0.20
  600. @uiToggle() enableRotate = true
  601. @uiInput() rotateSpeed = 2.0
  602. @uiToggle() enablePan = true
  603. @uiInput() panSpeed = 1.0
  604. @uiInput() autoPushTarget = false
  605. @uiInput() autoPullTarget = false
  606. @uiInput() minDistance = 0.35
  607. @uiInput() maxDistance = 1000
  608. @uiInput() minZoom = 0.01
  609. @uiInput() maxZoom = 1000
  610. @uiInput() minPolarAngle = 0
  611. @uiInput() maxPolarAngle = Math.PI
  612. @uiInput() minAzimuthAngle = -10000 // should be -Infinity but this breaks the UI
  613. @uiInput() maxAzimuthAngle = 10000
  614. }
  615. ```
  616. Check out the full source code:
  617. [./src/three/controls/OrbitControls3.ts](./src/three/controls/OrbitControls3.ts) for proper implementation
  618. See it in action: https://threepipe.org/examples/#camera-uiconfig/ Open the Camera UI and click on the Orbit Controls panel.
  619. There are many available decorators like `uiToggle`, `uiSlider`, `uiInput`, `uiNumber`, `uiColor`, `uiImage`.
  620. Check the complete list in the [uiconfig.js documentation](https://repalash.com/uiconfig.js/).
  621. The UI configuration can also be created using json objects in both typescript and javascript
  622. ```javascript
  623. const viewer = new ThreeViewer({...})
  624. const ui = viewer.addPluginSync(TweakpaneUiPlugin)
  625. const state = {
  626. position: new Vector3(),
  627. scale: 1,
  628. }
  629. ui.appendChild({
  630. type: 'folder',
  631. label: 'Custom UI',
  632. children: [
  633. {
  634. type: 'vec3',
  635. label: 'Position',
  636. property: [state, 'position']
  637. },
  638. {
  639. type: 'slider',
  640. label: ()=>'Scale', // everything can be a function as well.
  641. property: [state, 'scale'],
  642. bounds: [1, 2],
  643. stepSize: 0.1,
  644. }
  645. ]
  646. })
  647. ```
  648. TODO: create example/codepen for this
  649. ## Serialization
  650. Easy serialization of all threepipe and most three.js objects are supported out of the box using the Asset Manager.
  651. Fine control over serialization is also supported
  652. using the [ThreeSerialization](https://threepipe.org/docs/classes/ThreeSerialization.html) class
  653. Call `ThreeSerialization.serialize` on any object to serialize it.
  654. and `ThreeSerialization.deserialize` to deserialize the serialized object.
  655. This is done by performing a nested serialization of all the properties of the object.
  656. It's possible to implement custom serializers for custom types and classes and is done for three.js primitives,
  657. objects and plugins in threepipe
  658. To make a custom data class that is serializable,
  659. mark it using `@serializable` decorator and any properties using `@serialize` decorator.
  660. ```typescript
  661. @serializable('DataClass')
  662. class DataClass{
  663. @serialize() prop1 = 1
  664. @serialize() prop2 = 'string'
  665. @serialize() prop3 = new Vector3()
  666. @serialize() prop4 = new PhysicalMaterial()
  667. @serialize() prop4 = {
  668. prop1: 1,
  669. prop2: 'string',
  670. prop3: new Vector3(),
  671. prop4: new PhysicalMaterial(),
  672. }
  673. }
  674. const data = new DataClass()
  675. const serialized = ThreeSerialization.serialize(data)
  676. const deserialized = ThreeSerialization.deserialize(serialized)
  677. ```
  678. The classes without a `@serializable` decorator are serialized as plain objects.
  679. These can still include `@serialize` decorator to mark the properties are serializable
  680. but these classes cannot be deserialized into a new instance of the class.
  681. The ThreeViewer and plugins are an example of these.
  682. When deserialized they need an object to deserialize into.
  683. This ensures there is always just one instance.
  684. With this, the serialization system works like `toJSON` and `fromJSON` methods in three.js.
  685. Check the [plugin system](#plugin-system) below for more details on how to mark properties as serializable for plugins.
  686. ```typescript
  687. class CustomClass{
  688. @serialize() prop1 = 1
  689. @serialize() prop2 = 'string'
  690. @serialize() prop3 = new Vector3()
  691. @serialize() prop4 = new PhysicalMaterial()
  692. }
  693. const obj = new DataClass()
  694. const serialized = ThreeSerialization.serialize(data)
  695. // now to deserialize we need to pass in the object to deserialize into
  696. ThreeSerialization.deserialize(serialized, obj)
  697. ```
  698. ## Plugin System
  699. Threepipe includes a plugin system for adding additional features to the viewer in a modular way.
  700. The plugins can be added synchronously or asynchronously using `viewer.addPluginSync` and `viewer.addPlugin` methods respectively.
  701. It is recommended to create custom plugins for reusable features,
  702. as they provide built-in features for ui configuration,
  703. serialization, integration with editors etc and are easy to manage and tree-shake in the code.
  704. Check out the list of plugins in the [Plugin List](#threepipe-plugins) section below.
  705. To create new plugins,
  706. simply implement the `IViewerPlugin` interface or extend the [AViewerPluginSync](https://threepipe.org/docs/classes/AViewerPluginSync.html) or [AViewerPluginAsync](https://threepipe.org/docs/classes/AViewerPluginAsync.html) classes.
  707. The only difference is that in async the `onAdded` and `onRemove` functions are async
  708. Here is a sample plugin
  709. ```typescript
  710. @uiFolder("Sample Plugin") // This creates a folder in the Ui. (Supported by TweakpaneUiPlugin)
  711. export class SamplePlugin extends AViewerPluginSync<"sample-1" | "sample-2"> {
  712. // These are the list of events that this plugin can dispatch.
  713. static readonly PluginType = "SamplePlugin"; // This is required for serialization and handling plugins. Also used in viewer.getPluginByType()
  714. @uiToggle() // This creates a checkbox in the Ui. (Supported by TweakpaneUiPlugin)
  715. @serialize() // Adds this property to the list of serializable. This is also used when serializing to glb in AssetExporter.
  716. enabled = true;
  717. // A plugin can have custom properties.
  718. @uiSlider("Some Number", [0, 100], 1) // Adds a slider to the Ui, with custom bounds and step size (Supported by TweakpaneUiPlugin)
  719. @serialize("someNumber")
  720. @onChange(SamplePlugin.prototype._updateParams) // this function will be called whenevr this value changes.
  721. val1 = 0;
  722. // A plugin can have custom properties.
  723. @uiInput("Some Text") // Adds a slider to the Ui, with custom bounds and step size (Supported by TweakpaneUiPlugin)
  724. @onChange(SamplePlugin.prototype._updateParams) // this function will be called whenevr this value changes.
  725. @serialize()
  726. val2 = "Hello";
  727. @uiButton("Print Counters") // Adds a button to the Ui. (Supported by TweakpaneUiPlugin)
  728. public printValues = () => {
  729. console.log(this.val1, this.val2);
  730. this.dispatchEvent({ type: "sample-1", detail: { sample: this.val1 } }); // This will dispatch an event.
  731. }
  732. constructor() {
  733. super();
  734. this._updateParams = this._updateParams.bind(this);
  735. }
  736. private _updateParams() {
  737. console.log("Parameters updated.");
  738. this.dispatchEvent({ type: "sample-2" }); // This will dispatch an event.
  739. }
  740. onAdded(v: ThreeViewer): void {
  741. super.onAdded(v);
  742. // Do some initialization here.
  743. this.val1 = 0;
  744. this.val2 = "Hello";
  745. v.addEventListener("preRender", this._preRender);
  746. v.addEventListener("postRender", this._postRender);
  747. v.addEventListener("preFrame", this._preFrame);
  748. v.addEventListener("postFrame", this._postFrame);
  749. this._viewer!.scene.addEventListener("addSceneObject", this._objectAdded); // this._viewer can also be used while this plugin is attached.
  750. }
  751. onRemove(v: ThreeViewer): void {
  752. // remove dispose objects
  753. v.removeEventListener("preRender", this._preRender);
  754. v.removeEventListener("postRender", this._postRender);
  755. v.removeEventListener("preFrame", this._preFrame);
  756. v.removeEventListener("postFrame", this._postFrame);
  757. this._viewer!.scene.removeEventListener("addSceneObject", this._objectAdded); // this._viewer can also be used while this plugin is attached.
  758. super.onRemove(v);
  759. }
  760. private _objectAdded = (ev: IEvent<any>) => {
  761. console.log("A new object, texture or material is added to the scene.", ev.object);
  762. };
  763. private _preFrame = (ev: IEvent<any>) => {
  764. // This function will be called before each frame. This is called even if the viewer is not dirty, so it's a good place to do viewer.setDirty()
  765. };
  766. private _preRender = (ev: IEvent<any>) => {
  767. // This is called before each frame is rendered, only when the viewer is dirty.
  768. };
  769. // postFrame and postRender work the same way as preFrame and preRender.
  770. }
  771. ```
  772. Notes:
  773. * All plugins that are present in the dependencies array when the plugin is added to the viewer, are created and attached to the viewer in `super.onAdded`
  774. * Custom events can be dispatched with `this.dispatchEvent`, and subscribed to with `plugin.addEventListener`. The event type must be described in the class signature for typescript autocomplete to work.
  775. * Event listeners and other hooks can be added and removed in `onAdded` and `onRemove` functions for the viewer and other plugins.
  776. * To the viewer render the next frame, `viewer.setDirty()` can be called, or set `this.dirty = true` in preFrame and reset in postFrame to stop the rendering. (Note that rendering may continue if some other plugin sets the viewer dirty like `ProgressivePlugin` or any of the animation plugins). Check `isConverged` in `ProgressivePlugin` to check if its the final frame.
  777. * All Plugins which inherit from AViewerPlugin support serialisation. Create property `serializeWithViewer = false` to disable serialisation with the viewer in config and glb or `toJSON: any = undefined` to disable serialisation entirely
  778. * `plugin.toJSON()` and `plugin.fromJSON()` or `ThreeSerialization` can be used to serialize and deserialize plugins. `viewer.exportPluginConfig` and `viewer.importPluginConfig` also exist for this.
  779. * @serialize('label') decorator can be used to mark any public/private variable as serializable. label (optional) corresponds to the key in JSON.
  780. * @serialize supports instances of ITexture, IMaterial, all primitive types, simple JS objects, three.js math classes(Vector2, Vector3, Matrix3...), and some more.
  781. * uiDecorators can be used to mark properties and functions that will be shown in the Ui. The Ui shows up automatically when TweakpaneUiPlugin is added to the viewer. Plugins have special features in the UI for download preset and saving state.
  782. Check various plugins in the source code for more examples.
  783. # Viewer API
  784. [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html) - is the main entry point to 3d rendering on the canvas.
  785. - `.renderManager`: [ViewerRenderManager](https://threepipe.org/docs/classes/ViewerRenderManager.html) & [RenderManager](https://threepipe.org/docs/classes/RenderManager.html) & [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html) - Render manager for managing the rendering and composition pipeline, and provides helpers for rendering and render target management
  786. - `.renderer`: [IWebGLRenderer](https://threepipe.org/docs/interfaces/IWebGLRenderer.html) - for rendering. Instance of three.js [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer)
  787. - `.composer`: [EffectComposer2](https://threepipe.org/docs/classes/EffectComposer2.html) - for rendering passes. Instance of three.js [EffectComposer](https://threejs.org/docs/#api/en/postprocessing/EffectComposer)
  788. - `.context`: [WebGLRenderingContext](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) - WebGL rendering context
  789. - `.renderPass`: [ExtendedRenderPass](https://threepipe.org/docs/classes/ExtendedRenderPass.html) - Render pass for rendering the scene. Instance of three.js [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) with extra features
  790. - `.screenPass`: [ScreenPass](https://threepipe.org/docs/classes/ScreenPass.html) - Screen pass for rendering the final output. Instance of three.js [ShaderPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass) with extra features.
  791. - `.scene`: [RootScene](https://threepipe.org/docs/classes/RootScene.html) - Main scene used for rendering. Instance of three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene)
  792. - `.mainCamera`: [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html) - Main camera currently being used for rendering. Instance of three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera)
  793. - `.assetManager`: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) - Asset manager for loading, managing and exporting assets
  794. - `.importer`: [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html) - for importing assets
  795. - `.exporter`: [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html) - for exporting assets
  796. - `.materialManager`: [MaterialManager](https://threepipe.org/docs/classes/MaterialManager.html) - for managing materials and material extensions
  797. - `.plugins`: `Record`<`string`, [IViewerPlugin](https://threepipe.org/docs/interfaces/IViewerPlugin.html)> - Plugins added to the viewer
  798. - `.uiConfig`: [UiObjectConfig](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html) - UI confguration for the viewer. Used to automatically generate UIs for the viewer and plugins.
  799. ## ThreeViewer
  800. Source Code: [src/viewer/ThreeViewer.ts](./src/viewer/ThreeViewer.ts)
  801. API Reference: [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html)
  802. `ThreeViewer` is the main entry point to the viewer. It provides all the API for managing the scene, camera, rendering, plugins, etc.
  803. It is initialized with either a canvas element or a `HTMLElement` for the container.
  804. The canvas element is used for rendering, and the options are used to configure the viewer.
  805. If the canvas element is not provided, a new canvas element is created and appended to the container.
  806. More options can be passed in the constructor to configure various built-in plugins and rendering features in the viewer.
  807. ### Constructor
  808. ```typescript
  809. import {ThreeViewer, CameraViewPlugin} from 'threepipe'
  810. // Create a viewer. All options except canvas/container are optional
  811. const viewer = new ThreeViewer({
  812. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  813. // or a container like:
  814. // container: document.getElementById('mcontainer'),
  815. // container: document.body,
  816. // Set the render scale to render at device resolution
  817. renderScale: window.devicePixelRatio,
  818. // modify the screen shader: See ScreenPass and ScreenPass.glsl for more details
  819. screenShader: `diffuseColor = diffuseColor * 2.0;`,
  820. // Add TonemapPlugin
  821. tonemap: true,
  822. // Use MSAA(anti-aliasing)
  823. msaa: false,
  824. // Use Uint8 RGBM HDR Render Pipeline. Provides better performance with post-processing. RenderManager Uses Half-float if set to false.
  825. rgbm: true,
  826. // Use rendered gbuffer as depth-prepass / z-prepass.
  827. zPrepass: false,
  828. // Options for AssetManager
  829. assetManager: {
  830. // Use a custom CacheStorage
  831. storage: caches.open('threepipe-assetmanager'),
  832. },
  833. // Use DropzonePlugin to add support for file drag and drop
  834. // Enable and set properties
  835. dropzone: {
  836. // Set allowed extensions
  837. allowedExtensions: ['png', 'glb', 'gltf'],
  838. // Automatically add downloaded assets
  839. autoAdd: true
  840. // autoImport: true,
  841. // domElement: document.body,
  842. // addOptions: { ... }
  843. // importOptions: { ... }
  844. },
  845. // By default its false
  846. // dropzone: false,
  847. // To Enable without options
  848. // dropzone: true
  849. // Add some plugins after viewer creation.
  850. plugins: [CameraViewPlugin, new CustomPlugin()],
  851. // Shorthand to load files immediately after viewer initialization
  852. load: {
  853. src: 'https://example.com/file.glb',
  854. environment: 'https://example.com/file.hdr',
  855. background: 'https://example.com/file.png',
  856. },
  857. onLoad: (viewer) => {
  858. // Called when all the files are loaded
  859. },
  860. })
  861. ```
  862. Check the interface [ThreeViewerOptions](https://threepipe.org/docs/interfaces/ThreeViewerOptions.html) for all the options.
  863. To dispose off the viewer and all its resources call [`viewer.dispose()`](https://threepipe.org/docs/classes/ThreeViewer.html#dispose) method.
  864. To dispose only the scene objects and not the complete viewer, use `viewer.scene.disposeSceneModels()`
  865. ### Plugin Functions
  866. ```typescript
  867. import {ThreeViewer, TonemapPlugin, DepthBufferPlugin, NormalBufferPlugin} from 'threepipe'
  868. const viewer = new ThreeViewer({...})
  869. // Add a plugin
  870. const plugin = viewer.addPluginSync(new TonemapPlugin())
  871. // plugins can be added with just the class also
  872. const plugin2 = viewer.addPluginSync(TonemapPlugin)
  873. // Add multiple plugins at once
  874. viewer.addPluginsSync([
  875. TonemapPlugin,
  876. new NormalBufferPlugin(),
  877. DepthBufferPlugin,
  878. // ...
  879. ])
  880. // Get a plugin
  881. const plugin3 = viewer.getPlugin(TonemapPlugin)
  882. // Get or add a plugin, when not sure if the plugin is already added
  883. const plugin4 = viewer.getOrAddPluginSync(TonemapPlugin)
  884. // Remove a plugin
  885. viewer.removePluginSync(TonemapPlugin)
  886. ```
  887. Note: all sync functions above have async counterparts like `addPlugin`, `getOrAddPlugin`,
  888. `removePlugin` that are used for async plugins.
  889. There are no async plugins built-in to threepipe yet.
  890. ### Import/Export Functions
  891. ```typescript
  892. import {ThreeViewer} from 'threepipe'
  893. const viewer = new ThreeViewer({...})
  894. // Load a 3d model
  895. const object = await viewer.load<IObject3D>('https://example.com/file.glb')
  896. // Load a material
  897. const material = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  898. // Load an image
  899. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  900. // Import a model without adding to the scene
  901. const imported = await viewer.import('https://example.com/file.glb')
  902. // Export the complete scene with viewer configuraion
  903. const exportedScene = await viewer.exportScene({})
  904. // Export an object
  905. const exported = await viewer.export(object)
  906. // Export a material
  907. const exportedMaterial = await viewer.export(material)
  908. // Export a texture
  909. const exportedTexture = await viewer.export(texture)
  910. // Export viewer and plugins configurations
  911. const exportedConfig = await viewer.export(viewer)
  912. // Export plugin configuration
  913. const exportedPlugin = await viewer.exportPlugin(viewer.getPlugin(PluginClass))
  914. // Set Background Image
  915. await viewer.setBackgroundMap('https://example.com/file.png')
  916. // Set Environment Map
  917. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  918. // Add an imported object or a created three.js object to the scene
  919. viewer.addSceneObject(imported)
  920. ```
  921. [`viewer.load`](https://threepipe.org/docs/classes/ThreeViewer.html#load) - Loads a single asset by path or [IAsset](https://threepipe.org/docs/interfaces/IAsset.html) object, and adds to the scene if its 3d object or loads it if it's a configuration It is the same as [AssetManager.addAssetSingle](https://threepipe.org/docs/classes/AssetManager.html#addAssetSingle). Use [AssetManager.addAsset](https://threepipe.org/docs/classes/AssetManager.html#addAsset) to load multiple assets from the same path like in case of zip bundles.
  922. [`viewer.import`](https://threepipe.org/docs/classes/ThreeViewer.html#import) - Load a single asset but does not add to the scene or load the configuration. It is the same as [AssetManager.importer.importSingle](https://threepipe.org/docs/classes/AssetImporter.html#importSingle). Use [AssetManager.importer.import](https://threepipe.org/docs/classes/AssetImporter.html#import) to import multiple assets from the same path like in case of zip bundles.
  923. [`viewer.export`](https://threepipe.org/docs/classes/ThreeViewer.html#export) - Exports an object, material, texture, render target or plugin configuration and returns a Blob. It is similar to [AssetManager.exporter.exportObject](https://threepipe.org/docs/classes/AssetExporter.html#exportObject) but adds support for exporting plugin and self(viewer) configs.
  924. [`viewer.exportScene`](https://threepipe.org/docs/classes/ThreeViewer.html#exportScene) - Exports the scene model root and all configurations into a bundled `glb` file and returns a blob.
  925. [`viewer.exportPlugin`](https://threepipe.org/docs/classes/ThreeViewer.html#exportPlugin) - Exports a plugin configuration and returns a blob.
  926. [`viewer.setBackgroundMap`](https://threepipe.org/docs/classes/ThreeViewer.html#setBackgroundMap) - Sets the background map to the given texture or url. Also sets it as environment map if `setEnvironment` is `true` in the options.
  927. [`viewer.setEnvironmentMap`](https://threepipe.org/docs/classes/ThreeViewer.html#setEnvironmentMap) - Sets the environment map to the given texture or url. Also sets it as background if `setBackground` is `true` in the options.
  928. [`viewer.addSceneObject`](https://threepipe.org/docs/classes/ThreeViewer.html#addSceneObject) - Adds an imported object or a created three.js object to the scene model root. If an imported scene model root is passed, it will be loaded with viewer configuration, unless `importConfig` is `false` in the options.
  929. ### Frame/Rendering Events
  930. ```typescript
  931. import {ThreeViewer} from 'threepipe'
  932. const viewer = new ThreeViewer({...})
  933. // Add a callback to be called before every frame, irrespective of whether enything is being rendered that frame
  934. viewer.addEventListener('preFrame', (ev)=>{
  935. console.log(ev);
  936. // change something
  937. viewer.setDirty() // let the viewer know to re-render the scene from this frame
  938. })
  939. // Add a callback to be called after every frame, irrespective of whether enything was rendered that frame
  940. viewer.addEventListener('postFrame', (ev)=>{
  941. console.log(ev);
  942. // change something
  943. viewer.setDirty() // let the viewer know to re-render the scene from next frame
  944. })
  945. // Add a callback to be called before every render, only if something is being rendered that frame
  946. viewer.addEventListener('preRender', (ev)=>{
  947. // canvas is about to be rendered, or re-rendered for progressive rendering
  948. console.log(ev, viewer.renderManager.frameCount);
  949. })
  950. // Add a callback to be called after every render, only if something was rendered that frame
  951. viewer.addEventListener('postRender', (ev)=>{
  952. // canvas is rendered, or re-rendered for progressive rendering
  953. console.log(ev);
  954. })
  955. // Listen to viewer.setDirty() calls
  956. viewer.addEventListener('update', (ev)=>{
  957. // viewer.setDirty() was called by some plugin or code
  958. console.log(ev);
  959. })
  960. // to remove an event listener, first keep a reference to the callback
  961. const callback = (ev)=>{ return }
  962. viewer.addEventListener('preFrame', callback)
  963. // then remove it
  964. viewer.removeEventListener('preFrame', callback)
  965. // Add a callback to be called only once for an event
  966. viewer.doOnce('postFrame', () => viewer.canvas.toDataURL('image/png'))
  967. // Enable/disable rendering in the viewer
  968. viewer.renderEnabled = false
  969. // do something with the canvas or load assets
  970. await viewer.load('https://example.com/file.glb')
  971. await viewer.load('https://example.com/file1.glb')
  972. await viewer.load('https://example.com/file2.glb')
  973. viewer.renderEnabled = true // all the assets will be rendered together in the next frame
  974. ```
  975. Check the [IViewerEvent](https://threepipe.org/docs/interfaces/IViewerEvent.html) interface for all the event types.
  976. [`viewer.addEventListener`](https://threepipe.org/docs/classes/ThreeViewer.html#addEventListener) - Adds a callback to be called on the given event. The callback is called with an [IViewerEvent](https://threepipe.org/docs/interfaces/IViewerEvent.html) object.
  977. [`viewer.removeEventListener`](https://threepipe.org/docs/classes/ThreeViewer.html#removeEventListener) - Removes a callback from the given event.
  978. [`viewer.doOnce`](https://threepipe.org/docs/classes/ThreeViewer.html#doOnce) - Adds a callback to be called only once for the given event. The listener will be added and automatically removed after the first call.
  979. ### Utility Functions
  980. ```typescript
  981. import {ThreeViewer} from 'threepipe'
  982. const viewer = new ThreeViewer({...})
  983. // Set size
  984. viewer.setSize({width: 800, height: 600})
  985. // Traverse scene objects
  986. viewer.traverseSceneObjects((object) => {
  987. console.log(object)
  988. // do something with object
  989. })
  990. // If the size is set by css or manually by javascript use `resize` to update the viewer
  991. viewer.resize()
  992. // Trigger re-render with `setDirty` when something changes and viewer is not notified internally
  993. viewer.setDirty()
  994. // Get snapshot of the canvas as a blob
  995. const blob = await viewer.getScreenshotBlob({mimeTye: 'image/png', quality: 90})
  996. // Get snapshot of the canvas as a data url
  997. const dataUrl = await viewer.getScreenshotDataUrl({mimeTye: 'image/jpeg', quality: 85})
  998. // Dispose viewer and all resources
  999. viewer.canvas.remove() // canvas needs to be removed separately from the DOM
  1000. viewer.dispose()
  1001. ```
  1002. [`viewer.setSize`](https://threepipe.org/docs/classes/ThreeViewer.html#setSize) - Sets the size of the canvas and updates the renderer and the camera. If no width/height is passed, canvas is set to 100% of the container.
  1003. [`viewer.traverseSceneObjects`](https://threepipe.org/docs/classes/ThreeViewer.html#traverseSceneObjects) - Loop through all the objects in the scene model root hierarchy and calls the callback function with each object.
  1004. [`viewer.resize`](https://threepipe.org/docs/classes/ThreeViewer.html#resize) - Mark that the canvas is resized. If the size is changed, the renderer and all render targets are resized.
  1005. [`viewer.setDirty`](https://threepipe.org/docs/classes/ThreeViewer.html#setDirty) - Triggers re-render on next `requestAnimationFrame` call.
  1006. [`viewer.getScreenshotBlob`](https://threepipe.org/docs/classes/ThreeViewer.html#getScreenshotBlob) - Returns a blob of the canvas screenshot. The blob can be used to download the screenshot or upload to a server.
  1007. [`viewer.getScreenshotDataUrl`](https://threepipe.org/docs/classes/ThreeViewer.html#getScreenshotDataUrl) - Returns a data url of the canvas screenshot. The data url can be used to display the screenshot in an image element.
  1008. [`viewer.dispose`](https://threepipe.org/docs/classes/ThreeViewer.html#dispose) - Disposes the viewer and all its resources. Use this to dispose the viewer when it is no longer needed. Note: the canvas element is not removed from the DOM and needs to be removed separately.
  1009. ## RenderManager
  1010. Source Code: [src/viewer/ViewerRenderManager.ts](./src/viewer/ViewerRenderManager.ts), [src/rendering/RenderManager.ts](./src/rendering/RenderManager.ts), [src/rendering/RenderTargetManager.ts](./src/rendering/RenderTargetManager.ts)
  1011. API Reference: [ViewerRenderManager](https://threepipe.org/docs/classes/ViewerRenderManager.html), [RenderManager](https://threepipe.org/docs/classes/RenderManager.html), [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html)
  1012. It manages the rendering, composition/postprocessing of the scene and provides helpers for rendering and render target management.
  1013. ```typescript
  1014. const viewer = new ThreeViewer({...})
  1015. const renderManager = viewer.renderManager
  1016. // Get the effect composer
  1017. const composer = renderManager.composer
  1018. // Get the three.js webgl renderer
  1019. const renderer = renderManager.renderer
  1020. // Get the main Render Pass in the pipeline
  1021. const renderPass = renderManager.renderPass
  1022. // Get the main Screen Pass in the pipeline
  1023. const screenPass = renderManager.screenPass
  1024. // Set the render scale
  1025. renderManager.renderScale = Math.min(window.devicePixelRatio, 2)
  1026. // Register a custom composer pass
  1027. const customPass: IPipelinePass = new CustomPass()
  1028. renderManager.registerPass(customPass)
  1029. // Unregister a custom composer pass
  1030. renderManager.unregisterPass(customPass)
  1031. // The pipeline is automatically created and sorted based on dependencies in pipeline pass.
  1032. // To check the built pipeline
  1033. console.log(renderManager.pipeline)
  1034. // Set a custom render pipeline
  1035. renderManager.autoBuildPipeline = false
  1036. renderManager.pipeline = ['depth', 'render', 'screen']
  1037. // Check the total frames rendererd
  1038. console.log(renderManager.totalFrameCount)
  1039. // Get the current frame count in progressive rendering
  1040. console.log(renderManager.frameCount)
  1041. // Force reset shadows when some object is moved
  1042. renderManager.resetShadows()
  1043. // Render Target Management
  1044. // Get the main composer target
  1045. const composerTarget = renderManager.composerTarget
  1046. // clone the target to get a copy of the target with all the default options
  1047. const clonedTarget = composeTarget.clone()
  1048. // Create a render target, same size as the canvas. The target are automatically resized when the canvas is resized
  1049. const renderTarget = renderManager.createTarget({
  1050. sizeMultiplier: 1, // size multiplier from the canvas. 0.5 will be half width and height of the canvas
  1051. type: UnsignedByteType,
  1052. // ... // See CreateRenderTargetOptions for all options
  1053. })
  1054. // Create a render target of custom size
  1055. const renderTarget = renderManager.createTarget({
  1056. size: {
  1057. width: 1024,
  1058. height: 1024,
  1059. },
  1060. type: HalfFloatType,
  1061. // ...
  1062. })
  1063. // Dispose the render target
  1064. renderManager.disposeTarget(renderTarget)
  1065. // Create and release temporary targets for in-pass rendering.
  1066. const tempTarget = renderManager.getTempTarget({
  1067. sizeMultiplier: 0.5,
  1068. type: HalfFloatType,
  1069. // ...
  1070. })
  1071. // do something
  1072. renderManager.releaseTempTarget(tempTarget)
  1073. // Set how many temporary targets can remain in memory for a specific set of options
  1074. renderManager.maxTempPerKey = 10 // default = 5
  1075. // Copy/Blit a texture to the canvas or another render target with standard or a custom material
  1076. renderManager.blit(destination, {source: sourceTexture})
  1077. // Clear color of the canvas
  1078. renderManager.clearColor({r: 0, g: 0, b: 0, a: 1, depth: true, viewport: new Vector4(...)})
  1079. // Clear of a render target
  1080. renderManager.clearColor(renderTarget, {r: 0, g: 0, b: 0, a: 1, target: renderTarget})
  1081. // Export a render target to a blob. The type is automatically picked from exr to png based on the render target
  1082. const blob = renderManager.exportRenderTarget(renderTarget, 'auto')
  1083. // Export a render target to png/jpeg data url. This will clamp any floating point targets to fit in png/jpeg
  1084. const dataUrl = renderManager.renderTargetToDataUrl(renderTarget, 'image/png')
  1085. // Read render target pixels to array buffer. Returns Uint8Array|Uint16Array|Float32Array based on the render target type
  1086. const buffer = renderManager.renderTargetToBuffer(renderTarget)
  1087. ```
  1088. [`renderManager.composer`](https://threepipe.org/docs/classes/ViewerRenderManager.html#composer) - The three.js [EffectComposer](https://threejs.org/docs/#api/en/postprocessing/EffectComposer) used for rendering the pipeline.
  1089. [`renderManager.renderer`](https://threepipe.org/docs/classes/ViewerRenderManager.html#renderer) - The three.js [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) used for rendering
  1090. [`renderManager.context`](https://threepipe.org/docs/classes/ViewerRenderManager.html#context) - Access the WebGL rendering context for the canvas.
  1091. [`renderManager.renderPass`](https://threepipe.org/docs/classes/ViewerRenderManager.html#renderPass) - The main render pass used in the render pipeline. Instance of three.js [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) with extra features like z prepass, rgbm rendering, blurred transmission, msaa and other optimizations.
  1092. [`renderManager.screenPass`](https://threepipe.org/docs/classes/ViewerRenderManager.html#screenPass) - The main screen pass used in the render pipeline. Instance of three.js [ShaderPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass) with extra features like material extension, custom fragment, overriding read buffer, re-render to screen on change, etc
  1093. [`renderManager.renderScale`](https://threepipe.org/docs/classes/RenderManager.html#renderScale) - Sets the render scale. All targets are scaled by this factor. This is equivalent to calling `EffectComposer.setPixelRatio` and `WebGLRenderer.setPixelRatio` in three.js.
  1094. [`renderManager.resetShadows`](https://threepipe.org/docs/classes/RenderManager.html#resetShadows) - Resets all shadow maps in the scene. This is useful when some object is moved and the shadows need to be updated. This is automatically called when `scene.setDirty` or any `object.setDirty` is called, and during animation with plugins.
  1095. ### Rendering Pipeline
  1096. [`renderManager.registerPass`](https://threepipe.org/docs/classes/RenderManager.html#registerPass) - Registers a custom composer pass to the render pipeline. See [IPipelinePass](https://threepipe.org/docs/interfaces/IPipelinePass.html) interface.
  1097. [`renderManager.unregisterPass`](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) - Unregisters a custom composer pass from the render pipeline.
  1098. [`renderManager.pipeline`](https://threepipe.org/docs/classes/RenderManager.html#pipeline) - The render pipeline array. The array is automatically sorted based on dependencies in the pipeline passes.
  1099. [`renderManager.autoBuildPipeline`](https://threepipe.org/docs/classes/RenderManager.html#autoBuildPipeline) - If `true`, the pipeline is automatically created and sorted based on dependencies in pipeline pass. If `false`, the pipeline is built only once and is not changed after that. The default value is `true`.
  1100. [`renderManager.totalFrameCount`](https://threepipe.org/docs/classes/RenderManager.html#totalFrameCount) - The total frames rendered since the render manager was created.
  1101. [`renderManager.frameCount`](https://threepipe.org/docs/classes/RenderManager.html#frameCount) - The current frame count in progressive rendering. This is useful for progressive rendering effects like progressive shadows, gi, denoising, baking, anti-aliasing, and many other effects.
  1102. ### Render Targets management
  1103. [`renderManager.composerTarget`](https://threepipe.org/docs/classes/RenderManager.html#composerTarget), [`renderManager.composerTarget1`](https://threepipe.org/docs/classes/RenderManager.html#composerTarget1) - The main targets used in [EffectComposer2](https://threepipe.org/docs/classes/EffectComposer2)
  1104. [`renderManager.createTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#createTarget) - Creates a render target with the given options. The render target is automatically resized when the canvas is resized if `sizeMultiplier` is used. See [CreateRenderTargetOptions](https://threepipe.org/docs/interfaces/CreateRenderTargetOptions.html) for options
  1105. [`renderManager.disposeTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#disposeTarget) - Disposes a render target and removes it from the render target manager.
  1106. [`renderManager.getTempTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#getTempTarget) - Gets a temporary render target with the given options. The render target is automatically resized when the canvas is resized if `sizeMultiplier` is used. See [CreateRenderTargetOptions](https://threepipe.org/docs/interfaces/CreateRenderTargetOptions.html) for options
  1107. [`renderManager.releaseTempTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#releaseTempTarget) - Releases a temporary render target and adds it back to the render target manager.
  1108. [`renderManager.maxTempPerKey`](https://threepipe.org/docs/classes/RenderTargetManager.html#maxTempPerKey) - Sets how many temporary targets can remain in memory for a specific set of options. The default value is `5`.
  1109. ### Helpers
  1110. [`renderManager.blit`](https://threepipe.org/docs/classes/RenderManager.html#blit) - Blits a texture to the canvas or another render target with standard or a custom material. See [RendererBlitOptions](https://threepipe.org/docs/interfaces/RendererBlitOptions.html) for options.
  1111. [`renderManager.clearColor`](https://threepipe.org/docs/classes/RenderManager.html#clearColor) - Clears the color of the canvas or a render target.
  1112. [`renderManager.exportRenderTarget`](https://threepipe.org/docs/classes/RenderManager.html#exportRenderTarget) - Exports a render target to a blob. The type is automatically picked from exr to png based on the render target.
  1113. [`renderManager.renderTargetToDataUrl`](https://threepipe.org/docs/classes/RenderManager.html#renderTargetToDataUrl) - Exports a render target to png/jpeg data url string. This will clamp any floating point targets to fit in png/jpeg. See [RenderTargetToDataUrlOptions](https://threepipe.org/docs/interfaces/RenderTargetToDataUrlOptions.html) for options.
  1114. [`renderManager.renderTargetToBuffer`](https://threepipe.org/docs/classes/RenderManager.html#renderTargetToBuffer) - Reads render target pixels to a Uint8Array|Uint16Array|Float32Array array buffer.
  1115. ## RootScene
  1116. Source Code: [src/core/object/RootScene.ts](./src/core/object/RootScene.ts)
  1117. API Reference: [RootScene](https://threepipe.org/docs/classes/RootScene.html)
  1118. RootScene is the main scene that is rendered in the canvas.
  1119. It is an instance of three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene) with extra features including separation between model root and others,
  1120. backgroundColor, background map and background intensity,
  1121. environment map rotation and intensity, fixed env map direction patch, event bubbling in the scene hierarchy, scene config serialization, main camera management,
  1122. automatic active near far management based on scene bounds, disposing complete scene hierarchy, etc
  1123. ```typescript
  1124. const viewer = new ThreeViewer({...})
  1125. const scene = viewer.scene
  1126. // List oll loaded objects in the model root
  1127. console.log(scene.modelRoot.children)
  1128. // Set the background color
  1129. scene.setBackgroundColor('#ffffff')
  1130. // or
  1131. // scene.backgroundColor = new Color('#ffffff')
  1132. // or
  1133. // scene.backgroundColor.set('#ffffff')
  1134. // scene.onBackgroundChange() // this must be called when not using a setter or set function.
  1135. // Set a texture as background (or use viewer.setBackgroundMap). When both color and texture are set, they are multiplied
  1136. scene.background = customTexture
  1137. // Set the background same as the environment map
  1138. scene.background = 'environment' // background is automatically changed when the environment changes.
  1139. // or
  1140. // scene.background = scene.environment
  1141. // Set the background intensity
  1142. scene.backgroundIntensity = 2
  1143. // Set a texture as environment map (or use viewer.setEnvironmentMap)
  1144. scene.environment = customTexture
  1145. // Set the environment intensity
  1146. scene.envMapIntensity = 2
  1147. // Set the environment map rotation
  1148. scene.environment.rotation = Math.PI / 2
  1149. // Set Fixed env direction (rotate environment according the the camera)
  1150. scene.fixedEnvMapDirection = true
  1151. // Get the main camera used for rendering
  1152. const camera: PerspectiveCamera2 = scene.mainCamera
  1153. // Set camera props
  1154. camera.position.set(0, 0, 10)
  1155. camera.target.set(0, 0, 0)
  1156. camera.setDirty() // this needs to be called to notify the viewer to re-render the scene
  1157. // Traverse the model root hierarchy (or just use viewer.traverseSceneObjects)
  1158. scene.modelRoot.traverse((object) => {
  1159. console.log(object)
  1160. // do something with object
  1161. })
  1162. // Access the default camera (same as mainCamera if not changed explicitly)
  1163. const defaultCamera: ICamera = scene.defaultCamera
  1164. // Dispose all assets in the modelRoot
  1165. scene.disposeSceneModels()
  1166. // Remove all objects from the modelRoot
  1167. scene.clearSceneModels()
  1168. // Dispose the scene and all its resources and children
  1169. scene.dispose()
  1170. // Get bounds of the scene model root
  1171. const bounds = scene.getBounds(true, true) // true for precise bounds and ignore invisible
  1172. // Add an object to the scene or its model root depending on the options (or just use viewer.addSceneObject)
  1173. scene.addObject(object, {addToRoot: false}) // adds to the scene directly when addToRoot is true
  1174. // Load an imported model root from the asset importer
  1175. scene.loadModelRoot(object)
  1176. // notify that something has changed in the scene for re-render
  1177. scene.setDirty()
  1178. // notify that some object has changed in the scene for scene refresh(like shadow refresh, ground etc) and re-render
  1179. scene.refreshScene()
  1180. // or
  1181. scene.setDirty({refreshScene: true})
  1182. // set geometryChanged: false to prevent shadow recompute
  1183. scene.refreshScene({geometryChanged: false})
  1184. // refresh active near far. (in most cases this is done automatically and need not be called)
  1185. scene.refreshActiveNearFar()
  1186. ```
  1187. [`scene.modelRoot`](https://threepipe.org/docs/classes/RootScene.html#modelRoot) - The root object. All the objects loaded in the viewer are added to this object. And this is exported when exporting the gltf. Everything else like meta or UI objects can be added outside this.
  1188. [`scene.backgroundColor`](https://threepipe.org/docs/classes/RootScene.html#backgroundColor) - The background color of the scene. Can be a `Color | null`. This is not the same as `scene.background`. When both backgroundColor and background are set, they are multiplied.
  1189. [`scene.background`](https://threepipe.org/docs/classes/RootScene.html#background) - The background of the scene. This is the same as `scene.background` in three.js. This can be a texture or a color or null, but it's preferred to use `scene.backgroundColor` for color, and this for texture, then both can be used together.
  1190. [`scene.setBackgroundColor`](https://threepipe.org/docs/classes/RootScene.html#setBackgroundColor) - Set the background color from a string, number or color. Same as setting `backgroundColor` to a new color value.
  1191. [`scene.backgroundIntensity`](https://threepipe.org/docs/classes/RootScene.html#backgroundIntensity) - The background intensity of the scene. This is the same as `scene.backgroundIntensity` in three.js.
  1192. [`scene.environment`](https://threepipe.org/docs/classes/RootScene.html#environment) - The environment map of the scene. This is the same as `scene.environment` in three.js.
  1193. `scene.environment.rotation` - The rotation of the environment map around the y-axis.
  1194. [`scene.envMapIntensity`](https://threepipe.org/docs/classes/RootScene.html#envMapIntensity) - The environment intensity of the scene.
  1195. [`scene.fixedEnvMapDirection`](https://threepipe.org/docs/classes/RootScene.html#fixedEnvMapDirection) - If `true`, the environment map is rotated according to the camera. This is the same as `scene.fixedEnvMapDirection` in three.js.
  1196. [`scene.mainCamera`](https://threepipe.org/docs/classes/RootScene.html#mainCamera) - The main camera used for rendering. This is the same as `scene.mainCamera` in three.js.
  1197. [`scene.defaultCamera`](https://threepipe.org/docs/classes/RootScene.html#defaultCamera) - The default camera used for rendering. This is the same as `scene.defaultCamera` in three.js.
  1198. [`scene.disposeSceneModels`](https://threepipe.org/docs/classes/RootScene.html#disposeSceneModels) - Disposes all assets in the modelRoot.
  1199. [`scene.clearSceneModels`](https://threepipe.org/docs/classes/RootScene.html#clearSceneModels) - Removes all objects from the modelRoot.
  1200. [`scene.dispose`](https://threepipe.org/docs/classes/RootScene.html#dispose) - Disposes the scene and all its resources and children.
  1201. [`scene.getBounds`](https://threepipe.org/docs/classes/RootScene.html#getBounds) - Gets the bounds of the scene model root. Returns an instance of three.js [Box3](https://threejs.org/docs/#api/en/math/Box3) with min and max bounds according to parameters.
  1202. [`scene.addObject`](https://threepipe.org/docs/classes/RootScene.html#addObject) - Adds an object to the scene or its model root depending on the options. If `addToRoot` is `true`, the object is added to the model root, else it is added to the scene directly.
  1203. [`scene.setDirty`](https://threepipe.org/docs/classes/RootScene.html#setDirty) - Notifies that something has changed in the scene for re-render.
  1204. [`scene.refreshScene`](https://threepipe.org/docs/classes/RootScene.html#refreshScene) - Notifies that some object has changed in the scene for scene refresh(like shadow refresh, ground etc) and re-render. Slower than `setDirty`, as it refreshes shadows, updates bounds, etc.
  1205. [`scene.refreshActiveNearFar`](https://threepipe.org/docs/classes/RootScene.html#refreshActiveNearFar) - Refreshes active near far. (in most cases this is done automatically and need not be called)
  1206. [`scene.loadModelRoot`](https://threepipe.org/docs/classes/RootScene.html#loadModelRoot) - Loads an imported model root from the asset importer. This is used internally and in most cases, you don't need to call this.
  1207. ### Scene Events
  1208. RootScene dispatches many events that are useful when writing app logic or plugins
  1209. `'sceneUpdate'` - Listen to `refreshScene` called in RootScene. When some object changes.
  1210. `'addSceneObject'` - When a new object is added to the scene
  1211. `'mainCameraChange'` - When the main camera is changed to some other camera.
  1212. `'mainCameraUpdate'` - When some properties in the current main camera has changed.
  1213. `'environmentChanged'` - When the environment map changes
  1214. `'backgroundChanged'` - When the background map or color changes
  1215. `'materialUpdate`' - When a material in the scene has updated. (setDirty called on the material)
  1216. `'objectUpdate`' - When a object in the scene has updated. (setDirty called on the object)
  1217. `'textureUpdate`' - When a texture in the scene has updated. (setDirty called on the texture)
  1218. `'cameraUpdate`' - When a camera in the scene has updated.
  1219. (setDirty called on the camera)
  1220. `'geometryUpdate`' - When a geometry in the scene has updated.
  1221. (setDirty called on the geometry)
  1222. `'geometryChanged`' - When a geometry is changed on any mesh
  1223. `'materialChanged'` - When a material is changed on any mesh
  1224. Check [IObject3DEventTypes](https://threepipe.org/docs/interfaces/IObject3DEventTypes.html) and[ISceneEventTypes](https://threepipe.org/docs/interfaces/ISceneEventTypes.html) for more information.
  1225. ## ICamera
  1226. Source Code: [src/core/camera/PerspectiveCamera2.ts](./src/core/camera/PerspectiveCamera2.ts), [src/core/ICamera.ts](./src/core/ICamera.ts)
  1227. API Reference: [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html), [ICamera](https://threepipe.org/docs/interfaces/ICamera.html)
  1228. ICamera is an interface for a camera that extends the three.js [Camera](https://threejs.org/docs/#api/en/cameras/Camera).
  1229. PerspectiveCamera2 implements the interface,
  1230. extending from three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) with extra features like target, automatic aspect management, automatic near far management(from RootScene), camera control attachment and hooks(like OrbitControls) and the ability to set as the main camera in the root scene.
  1231. ```typescript
  1232. import {OrbitControls3} from './OrbitControls3'
  1233. const viewer = new ThreeViewer({...})
  1234. const camera: PerspectiveCamera2 = viewer.scene.mainCamera
  1235. // Set the camera position
  1236. camera.position.set(0, 0, 10)
  1237. // Set the camera target (where the camera looks at)
  1238. camera.target.set(0, 0, 0)
  1239. // Set the camera fov
  1240. camera.fov = 45
  1241. // Set the camera aspect ratio
  1242. camera.autoAspect = false // disable automatic aspect management based on the canvas size
  1243. camera.aspect = 1
  1244. // Set camera near far bounds.
  1245. // Near, Far plane will be calculated automatically within these limits
  1246. // Try changing these values when encountering z-fighting issues or far-plane clipping
  1247. camera.minNearPlane = 0.5 // min near plane
  1248. camera.maxFarPlane = 10 // max far plane
  1249. // Set a custom camera near far
  1250. camera.autoNearFar = false // disable automatic near far management based on the scene bounds
  1251. camera.minNearPlane = 0.1 // near plane
  1252. camera.maxFarPlane = 1000 // far plane
  1253. // this needs to be called to notify the viewer to re-render the scene
  1254. // in most cases this is done internally. But calling this does not have much impact
  1255. camera.setDirty()
  1256. // Check if user can interact with the camera. Also checks if its the main camera.
  1257. console.log(camera.canUserInteract)
  1258. // Get the camera controls (orbit controls for the default camera)
  1259. const controls: OrbitControls3 = camera.controls
  1260. // Disable controls
  1261. controls.enabled = false
  1262. // Change the controls mode
  1263. camera.controlsMode = 'none' // this will remove the current controls.
  1264. // Register a custom camera controls
  1265. camera.setControlsCtor('customOrbit', (camera, domElement) => new CustomOrbitControls(camera, domElement))
  1266. // Set the camera controls
  1267. camera.controlsMode = 'customOrbit' // this will initialize the controls with the customOrbit constructor and set it on the camera
  1268. // Disable interactions to the camera. (eg when animating)
  1269. camera.interactionsEnabled = false
  1270. // Force refresh aspect ratio (this is done automatically with a ResizeObserver on the canvas in the viewer)
  1271. camera.refreshAspect()
  1272. // Set the camera as the main camera
  1273. camera.activateMain()
  1274. // Deactivate the camera as the main camera
  1275. camera.deactivateMain()
  1276. ```
  1277. [`camera.target`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#target) - The target of the camera. This is the same as `controls.target` in three.js. The target is always in world-space coordinates, as opposed to position, rotation, and scale which are always relative to their parent.
  1278. [`camera.autoAspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#autoAspect) - If `true`, the aspect ratio is automatically calculated based on the canvas size.
  1279. [`camera.aspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#aspect) - The aspect ratio of the camera. This is the same as `camera.aspect` in three.js. This is only used when `camera.autoAspect` is `false`.
  1280. [`camera.minNearPlane`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#minNearPlane) - The minimum near plane of the camera. This is the same as `camera.near` in three.js when `camera.autoNearFar` is `false`, otherwise it is the minimum near plane distance from the camera allowed when computing automatically
  1281. [`camera.maxFarPlane`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#maxFarPlane) - The maximum far plane of the camera. This is the same as `camera.far` in three.js when `camera.autoNearFar` is `false`, otherwise it is the maximum far plane distance from the camera allowed when computing automatically
  1282. [`camera.autoNearFar`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#autoNearFar) - If `true` (default), the near and far planes are automatically calculated based on the scene bounds.
  1283. [`camera.setDirty`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setDirty) - Notifies that something has changed in the camera for re-render.
  1284. [`camera.canUserInteract`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#canUserInteract) - Checks if user can interact with the camera. Also checks if it's the main camera.
  1285. [`camera.controls`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#controls) - Get the current camera controls set on the camera. This can be changed by changing `controlsMode`
  1286. [`camera.controlsMode`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#controlsMode) - Get or set the current controls that are attached to the camera. More modes can be registered with `setControlsCtor`. Default for the default camera is `orbit` and `none` for any new cameras.
  1287. [`camera.setControlsCtor`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setControlsCtor) - Register a custom camera controls constructor. The controls can be set by setting `controlsMode` to the key/name of the controls.
  1288. [`camera.interactionsEnabled`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#interactionsEnabled) - If `true`, the camera can be interacted with. This is useful when animating the camera or using the window scroll or programmatically automating the viewer.
  1289. [`camera.refreshAspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#refreshAspect) - Force refresh aspect ratio (this is done automatically with a ResizeObserver on the canvas in the viewer or when `viewer.resize()` is called)
  1290. [`camera.activateMain`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#activateMain) - Set the camera as the main camera. This is the same as doing `scene.mainCamera = camera`. The camera needs to be in the scene hierarchy for this to work.
  1291. [`camera.deactivateMain`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#deactivateMain) - Deactivate the camera as the main camera.
  1292. See also [CameraViewPlugin](#cameraviewplugin) for camera focus animation.
  1293. ## AssetManager
  1294. Source Code: [src/assetmanager/AssetManager.ts](./src/assetmanager/AssetManager.ts)
  1295. API Reference: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html)
  1296. `AssetManager` is a class that manages the loading and exporting of assets and provides helpers for caching assets. It is used internally in the viewer and can be used to load assets outside the viewer. It provides a modular framework for adding more asset loaders and exporters.
  1297. ```typescript
  1298. const viewer = new ThreeViewer({...})
  1299. const assetManager = viewer.assetManager
  1300. // Add an asset or an asset bundle
  1301. const assets = await assetManager.addAsset('https://example.com/model.zip')
  1302. // or
  1303. const assets = await assetManager.addAsset({
  1304. path: 'https://example.com/model.zip',
  1305. file: blob,
  1306. })
  1307. // Get the storage used in the asset manager for caching
  1308. const storage: Cache | Storage = assetManager.storage
  1309. // Get the importer. Provides low level functions to import assets
  1310. const importer = assetManager.importer
  1311. // import a file by asset or url
  1312. const file = await importer.import('https://example.com/model.gltf')
  1313. // Import a Map<string, File> from drag drop
  1314. const res = await importer.importFiles(mapOfFiles, {})
  1315. // Register a custom path that maps to a File object. Useful when some file types have path references to other files.
  1316. importer.registerFile('/myFile.png', file) // this returns the three.js loader for that kind of file.
  1317. // Unregister the path
  1318. importer.unregisterFile('/myFile.png')
  1319. // Unregister all files and clear the loader cache(memory, not storage)
  1320. importer.clearCache()
  1321. // Add custom importers (check extra load plugins for more examples)
  1322. importer.addImporter(new Importer(class extends PLYLoader implements ILoader {
  1323. transform(res: BufferGeometry, _: AnyOptions): Mesh | undefined {
  1324. return res ? new Mesh(res, new PhysicalMaterial({color: new Color(1, 1, 1)})) : undefined
  1325. }
  1326. }, ['ply'], ['text/plain+ply'], false))
  1327. // Get the exporter. Provides low level functions to export assets
  1328. const exporter = assetManager.exporter
  1329. // Export any IObject3D, IMaterial, ITexture, IRenderTarget
  1330. const exported = exporter.exportObject(obj, options)
  1331. // Add a custom exporter
  1332. exporter.addExporter({
  1333. ext: ['gltf', 'glb'], // file extensions
  1334. extensions: [], // extensions for the exporter
  1335. ctor: (assetExporter, iexporter) => {
  1336. return new GLTFExporter2()
  1337. }
  1338. })
  1339. // Material Manager
  1340. const materialManager = assetManager.materialManager
  1341. // Create a material of type
  1342. const mat = materialManager.create('physical')
  1343. const mat2 = materialManager.create('unlit')
  1344. // find or create a material by uuid
  1345. const mat = materialManager.findOrCreate('00000000-0000-0000-0000-000000000000', {color: '#ffffff'})
  1346. // find a material creation template
  1347. const template = materialManager.findTemplate('physical')
  1348. // Get all materials
  1349. const materials = materialManager.getAllMaterials()
  1350. // Get all materials of type
  1351. const materials = materialManager.getMaterialsOfType(PhysicalMaterial.TypeSlug)
  1352. // register a custom material to the manager for tracking and extensions
  1353. // Note all materials created in threepipe internally are registered automatically on creation or when added to any scene object.
  1354. materialManager.registerMaterial(customMat)
  1355. // unregister
  1356. materialManager.unregisterMaterial(customMat)
  1357. // clear all material references
  1358. materialManager.clearMaterials()
  1359. // Register a custom material template
  1360. materialManager.registerTemplate({
  1361. generator: (params: any) => new PhysicalMaterial(params),
  1362. name: 'custom',
  1363. materialType: PhysicalMaterial.TYPE,
  1364. params: {
  1365. color: '#ffffff',
  1366. roughness: 0.5,
  1367. metalness: 0.5,
  1368. },
  1369. })
  1370. const mat3 = materialManager.create('custom')
  1371. // convert a standard three.js material to threepipe material
  1372. const mat4 = materialManager.convertToIMaterial(new ShadowMaterial(), {materialTemplate: 'test'})
  1373. // register a custom material extension for all materials in the viewer
  1374. materialManager.registerMaterialExtension(customExtension)
  1375. // unregister
  1376. materialManager.unregisterMaterialExtension(customExtension)
  1377. // remove all extensions
  1378. materialManager.clearExtensions()
  1379. // Apply a material properties to other material(s) in the scene by name or uuid
  1380. materialManager.applyMaterial(goldMaterial, 'METAL') // this will copy the properties from goldMaterial to all the materials(or objects) in the viewer with the name METAL.
  1381. // export a material as JSON. Note: use AssetExporter instead to export all the embedded assets and properties properly.
  1382. const blob = materialManager.exportMaterial(mat)
  1383. // dispose manager and all materials.
  1384. materialManager.dispose()
  1385. ```
  1386. [`assetManager.addAsset`](https://threepipe.org/docs/classes/AssetManager.html#addAsset) - Add an asset or an asset bundle. Returns a promise that resolves to an array of asset objects. An asset can contain multiple objects, hence an array is returned. Use shorthand `viewer.load(path)` to load a single asset from a single file.
  1387. [`assetManager.storage`](https://threepipe.org/docs/classes/AssetManager.html#storage) - Get the storage used in the asset manager for caching. This is the storage that can be passed in the `ThreeViewer` contructor options.
  1388. [`assetManager.importer`](https://threepipe.org/docs/classes/AssetManager.html#importer) - Get the importer. Provides low-level functions to import assets. This is an instance of [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html).
  1389. [`assetManager.exporter`](https://threepipe.org/docs/classes/AssetManager.html#exporter) - Get the exporter. Provides low-level functions to export assets. This is an instance of [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html).
  1390. ### AssetImporter
  1391. [`importer.import`](https://threepipe.org/docs/classes/AssetImporter.html#import) - Import a file by asset or url. Returns a promise that resolves to a [File](https://threepipe.org/docs/classes/File.html) object.
  1392. [`importer.importFiles`](https://threepipe.org/docs/classes/AssetImporter.html#importFiles) - Import a Map<string, File> from drag and drop. Returns a promise that resolves to a Map<string, any[]> of imported object arrays.
  1393. [`importer.registerFile`](https://threepipe.org/docs/classes/AssetImporter.html#registerFile) - Register a custom path that maps to a File object. Useful when some file types have path references to other files. Like when importing a .zip with a .gltf file that references a .bin file, or when loading remote files from custom local cache implementation.
  1394. [`importer.unregisterFile`](https://threepipe.org/docs/classes/AssetImporter.html#unregisterFile) - Unregister the path.
  1395. [`importer.clearCache`](https://threepipe.org/docs/classes/AssetImporter.html#clearCache) - Unregister all the registered files and clear the loader cache(memory cache, not cache-storage).
  1396. [`importer.addImporter`](https://threepipe.org/docs/classes/AssetImporter.html#addImporter) - Add custom importers (check extra load plugins for more examples). This allows to pass a class to a ILoader, that is used to import assets. Loaders are only created when a file is being loaded of that type. And they remain in the loader cache until `clearCache` or `clearLoaderCache` is called.
  1397. ### AssetExporter
  1398. [`exporter.exportObject`](https://threepipe.org/docs/classes/AssetExporter.html#exportObject) - Export any IObject3D, IMaterial, ITexture, IRenderTarget. Returns a promise that resolves to an exported object. Use `viewer.export` or `AssetExporterPlugin`, which provide more features and shortcuts to export viewer, scene and plugins as well.
  1399. [`exporter.addExporter`](https://threepipe.org/docs/classes/AssetExporter.html#addExporter) - Add a custom exporter for a custom file type.
  1400. ### MaterialManager
  1401. [`materialManager.create`](https://threepipe.org/docs/classes/MaterialManager.html#create) - Create a new material of a given type and with passed properties. Returns an implementation of [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  1402. [`materialManager.findOrCreate`](https://threepipe.org/docs/classes/MaterialManager.html#findOrCreate) - Find or create a material by uuid. Returns an instance of [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html). If a material with the uuid exists, it is returned, else a new material is created with the passed properties.
  1403. [`materialManager.findTemplate`](https://threepipe.org/docs/classes/MaterialManager.html#findTemplate) - Find a material creation template. Returns an instance of [IMaterialTemplate](https://threepipe.org/docs/interfaces/IMaterialTemplate.html). Material templates are used to create materials of a given type with default properties.
  1404. [`materialManager.getAllMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#getAllMaterials) - Get all materials registered with the manager.
  1405. [`materialManager.getMaterialsOfType`](https://threepipe.org/docs/classes/MaterialManager.html#getMaterialsOfType) - Get all materials of a specific type. Pass in the typeslug from the class like `pmat` or `dmat` to identify the material.
  1406. [`materialManager.registerMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#registerMaterial) - Register a new material to the manager for tracking and extensions. Note: all materials created in threepipe internally or any that are set to any object in the scene are registered automatically on creation or when used
  1407. [`materialManager.unregisterMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterial) - Unregister a material from the manager.
  1408. [`materialManager.clearMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#clearMaterials) - Clear all registered material references.
  1409. [`materialManager.registerTemplate`](https://threepipe.org/docs/classes/MaterialManager.html#registerTemplate) - Register a custom material template. Requires an instance of [IMaterialTemplate](https://threepipe.org/docs/interfaces/IMaterialTemplate.html). Material templates are used to create materials of a given type with default properties.
  1410. [`materialManager.convertToIMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#convertToIMaterial) - Convert/upgrade a standard three.js material to threepipe material, by making it conform to [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  1411. [`materialManager.registerMaterialExtension`](https://threepipe.org/docs/classes/MaterialManager.html#registerMaterialExtension) - Register a custom material extension for all materials in the viewer. Requires an instance of [IMaterialExtension](https://threepipe.org/docs/interfaces/IMaterialExtension.html). Material extensions are used to add custom properties, methods, uniforms, defines, shader patches etc to predefined materials. The extensions are added to the material when the mateiral or extension is registered to the manager.
  1412. [`materialManager.unregisterMaterialExtension`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterialExtension) - Unregister a material extension from the manager.
  1413. [`materialManager.clearExtensions`](https://threepipe.org/docs/classes/MaterialManager.html#clearExtensions) - Remove all material extensions from the manager.
  1414. [`materialManager.applyMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#applyMaterial) - Apply a material properties to other material(s) in the scene by name or uuid. This is useful when you want to change the properties of all materials with a given name or uuid. This can also be a regex, in that case a regex.match will be performed on the material/object name.
  1415. [`materialManager.exportMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#exportMaterial) - Export a material as JSON. Note: use `viewer.export` or `AssetExporter` instead to export all the embedded assets properly.
  1416. [`materialManager.dispose`](https://threepipe.org/docs/classes/MaterialManager.html#dispose) - Dispose manager and all materials.
  1417. # Threepipe Plugins
  1418. ThreePipe has a simple plugin system that allows you to easily add new features to the viewer. Plugins can be added to the viewer using the `addPlugin` and `addPluginSync` methods. The plugin system is designed to be modular and extensible. Plugins can be added to the viewer at any time and can be removed using the `removePlugin` and `removePluginSync` methods.
  1419. ## TonemapPlugin
  1420. [//]: # (todo: image)
  1421. Example: https://threepipe.org/examples/#tonemap-plugin/
  1422. Source Code: [src/plugins/postprocessing/TonemapPlugin.ts](./src/plugins/postprocessing/TonemapPlugin.ts)
  1423. API Reference: [TonemapPlugin](https://threepipe.org/docs/classes/TonemapPlugin.html)
  1424. TonemapPlugin adds a post-processing material extension to the ScreenPass in render manager
  1425. that applies tonemapping to the color. The tonemapping operator can be changed
  1426. by setting the `toneMapping` property of the plugin. The default tonemapping operator is `ACESFilmicToneMapping`.
  1427. Other Tonemapping properties can be like `exposure`, `contrast` and `saturation`
  1428. TonemapPlugin is added by default in ThreeViewer unless `tonemap` is set to `false` in the options.
  1429. ## DropzonePlugin
  1430. [//]: # (todo: image)
  1431. Example: https://threepipe.org/examples/#dropzone-plugin/
  1432. Source Code: [src/plugins/interaction/DropzonePlugin.ts](./src/plugins/interaction/DropzonePlugin.ts)
  1433. API Reference: [DropzonePlugin](https://threepipe.org/docs/classes/DropzonePlugin.html)
  1434. DropzonePlugin adds support for drag and drop of local files to automatically import, process and load them into the viewer.
  1435. DropzonePlugin can be added by default in ThreeViewer
  1436. by setting the `dropzone` property to `true` or an object of `DropzonePluginOptions` in the options.
  1437. ```typescript
  1438. import {DropzonePlugin, ThreeViewer} from 'threepipe'
  1439. const viewer = new ThreeViewer({
  1440. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  1441. dropzone: true, // just set to true to enable drag drop functionatility in the viewer
  1442. })
  1443. ```
  1444. To set custom options,
  1445. pass an object of [DropzonePluginOptions](https://threepipe.org/docs/interfaces/DropzonePluginOptions.html) type to the `dropzone` property.
  1446. ```typescript
  1447. import {DropzonePlugin, ThreeViewer} from 'threepipe'
  1448. const viewer = new ThreeViewer({
  1449. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  1450. dropzone: { // this can also be set to true and configured by getting a reference to the DropzonePlugin
  1451. allowedExtensions: ['gltf', 'glb', 'hdr', 'png', 'jpg', 'json', 'fbx', 'obj', 'bin', 'exr'], // only allow these file types. If undefined, all files are allowed.
  1452. addOptions: {
  1453. disposeSceneObjects: true, // auto dispose of old scene objects
  1454. autoSetEnvironment: true, // when hdr is dropped
  1455. autoSetBackground: true, // when any image is dropped
  1456. autoCenter: true, // auto center the object
  1457. autoScale: true, // auto scale according to radius
  1458. autoScaleRadius: 2,
  1459. license: 'Imported from dropzone', // Any license to set on imported objects
  1460. importConfig: true, // import config from file
  1461. },
  1462. // check more options in the DropzonePluginOptions interface
  1463. },
  1464. })
  1465. ```
  1466. ## ProgressivePlugin
  1467. [//]: # (todo: image)
  1468. Example: https://threepipe.org/examples/#progressive-plugin/
  1469. Source Code: [src/plugins/postprocessing/ProgressivePlugin.ts](./src/plugins/pipeline/ProgressivePlugin.ts)
  1470. API Reference: [ProgressivePlugin](https://threepipe.org/docs/classes/ProgressivePlugin.html)
  1471. Progressive Plugin adds a post-render pass to blend the last frame with the current frame.
  1472. This is used as a dependency in other plugins for progressive rendering effect which is useful for progressive shadows, gi, denoising, baking, anti-aliasing, and many other effects.
  1473. ## DepthBufferPlugin
  1474. [//]: # (todo: image)
  1475. Example: https://threepipe.org/examples/#depth-buffer-plugin/
  1476. Source Code: [src/plugins/pipeline/DepthBufferPlugin.ts](./src/plugins/pipeline/DepthBufferPlugin.ts)
  1477. API Reference: [DepthBufferPlugin](https://threepipe.org/docs/classes/DepthBufferPlugin.html)
  1478. Depth Buffer Plugin adds a pre-render pass to the render manager and renders a depth buffer to a target. The render target can be accessed by other plugins throughout the rendering pipeline to create effects like depth of field, SSAO, SSR, etc.
  1479. ```typescript
  1480. import {ThreeViewer, DepthBufferPlugin} from 'threepipe'
  1481. const viewer = new ThreeViewer({...})
  1482. const depthPlugin = viewer.addPluginSync(new DepthBufferPlugin(HalfFloatType))
  1483. const depthTarget = depthPlugin.target;
  1484. // Use the depth target by accesing `depthTarget.texture`.
  1485. ```
  1486. The depth values are based on camera near far values, which are controlled automatically by the viewer. To manually specify near, far values and limits, it can be set in the camera userData. Check the [example](https://threepipe.org/examples/#depth-buffer-plugin/) for more details.
  1487. ## NormalBufferPlugin
  1488. [//]: # (todo: image)
  1489. Example: https://threepipe.org/examples/#normal-buffer-plugin/
  1490. Source Code: [src/plugins/pipeline/NormalBufferPlugin.ts](./src/plugins/pipeline/NormalBufferPlugin.ts)
  1491. API Reference: [NormalBufferPlugin](https://threepipe.org/docs/classes/NormalBufferPlugin.html)
  1492. Normal Buffer Plugin adds a pre-render pass to the render manager and renders a normal buffer to a target. The render target can be accessed by other plugins throughout the rendering pipeline to create effects like SSAO, SSR, etc.
  1493. Note: Use [`DepthNormalBufferPlugin`](#DepthNormalBufferPlugin) if using both `DepthBufferPlugin` and `NormalBufferPlugin` to render both depth and normal buffers in a single pass.
  1494. ```typescript
  1495. import {ThreeViewer, NormalBufferPlugin} from 'threepipe'
  1496. const viewer = new ThreeViewer({...})
  1497. const normalPlugin = viewer.addPluginSync(new NormalBufferPlugin())
  1498. const normalTarget = normalPlugin.target;
  1499. // Use the normal target by accessing `normalTarget.texture`.
  1500. ```
  1501. ## GBufferPlugin
  1502. todo
  1503. ## PickingPlugin
  1504. [//]: # (todo: image)
  1505. Example: https://threepipe.org/examples/#picking-plugin/
  1506. Source Code: [src/plugins/pipeline/PickingPlugin.ts](./src/plugins/interaction/PickingPlugin.ts)
  1507. API Reference: [PickingPlugin](https://threepipe.org/docs/classes/PickingPlugin.html)
  1508. Picking Plugin adds support for selecting and hovering over objects in the viewer with user interactions and selection widgets.
  1509. When the plugin is added to the viewer, it starts listening to the mouse move and click events over the canvas.
  1510. When an object is clicked, it is selected,
  1511. and if a UI plugin is added, the uiconfig for the selected object is populated in the interface.
  1512. The events `selectedObjectChanged`, `hoverObjectChanged`, and `hitObject` can be listened to on the plugin.
  1513. Picking plugin internally uses [ObjectPicker](https://threepipe.org/docs/classes/ObjectPicker.html),
  1514. check out the documentation or source code for more information.
  1515. ```typescript
  1516. import {ThreeViewer, PickingPlugin} from 'threepipe'
  1517. const viewer = new ThreeViewer({...})
  1518. const pickingPlugin = viewer.addPluginSync(new PickingPlugin())
  1519. // Hovering events are also supported, but since its computationally expensive for large scenes it is disabled by default.
  1520. pickingPlugin.hoverEnabled = true
  1521. pickingPlugin.addEventListener('hitObject', (e)=>{
  1522. // This is fired when the user clicks on the canvas.
  1523. // The selected object hasn't been changed yet, and we have the option to change it or disable selection at this point.
  1524. // e.intersects.selectedObject contains the object that the user clicked on.
  1525. console.log('Hit: ', e.intersects.selectedObject)
  1526. // It can be changed here
  1527. // e.intersects.selectedObject = e.intersects.selectedObject.parent // select the parent
  1528. // e.intersects.selectedObject = null // unselect
  1529. // Check other properties on the event like intersects, mouse position, normal etc.
  1530. console.log(e)
  1531. })
  1532. pickingPlugin.addEventListener('selectedObjectChanged', (e)=>{
  1533. // This is fired when the selected object is changed.
  1534. // e.object contains the new selected object. It can be null if nothing is selected.
  1535. console.log('Selected: ', e.object)
  1536. })
  1537. // Objects can be programmatically selected and unselected
  1538. // to select
  1539. pickingPlugin.setSelectedObject(object)
  1540. // get the selected object
  1541. console.log(pickingPlugin.getSelectedObject())
  1542. // to unselect
  1543. pickingPlugin.setSelectedObject(null)
  1544. // Select object with camera animation to the object
  1545. pickingPlugin.setSelectedObject(object, true)
  1546. pickingPlugin.addEventListener('hoverObjectChanged', (e)=>{
  1547. // This is fired when the hovered object is changed.
  1548. // e.object contains the new hovered object.
  1549. console.log('Hovering: ', e.object)
  1550. })
  1551. ```
  1552. ## GLTFAnimationPlugin
  1553. [//]: # (todo: image)
  1554. Example: https://threepipe.org/examples/#gltf-animation-plugin/
  1555. Source Code: [src/plugins/animation/GLTFAnimationPlugin.ts](./src/plugins/animation/GLTFAnimationPlugin.ts)
  1556. API Reference: [GLTFAnimationPlugin](https://threepipe.org/docs/classes/GLTFAnimationPlugin.html)
  1557. Manages playback of GLTF animations.
  1558. The GLTF animations can be created in any 3d software that supports GLTF export like Blender.
  1559. If animations from multiple files are loaded, they will be merged in a single root object and played together.
  1560. The time playback is managed automatically, but can be controlled manually by setting {@link autoIncrementTime} to false and using {@link setTime} to set the time.
  1561. This plugin is made for playing, pausing, stopping, all the animations at once, while it is possible to play individual animations, it is not recommended.
  1562. To play individual animations, with custom choreography, use the {@link GLTFAnimationPlugin.animations} property to get reference to the animation clips and actions. Create your own mixers and control the animation playback like in three.js
  1563. ## PopmotionPlugin
  1564. [//]: # (todo: image)
  1565. Example: https://threepipe.org/examples/#popmotion-plugin/
  1566. Source Code: [src/plugins/animation/PopmotionPlugin.ts](./src/plugins/animation/PopmotionPlugin.ts)
  1567. API Reference: [PopmotionPlugin](https://threepipe.org/docs/classes/PopmotionPlugin.html)
  1568. Provides animation/tweening capabilities to the viewer using the [popmotion.io](https://popmotion.io/) library.
  1569. Overrides the driver in popmotion to sync with the viewer and provide ways to store and stop animations.
  1570. ```typescript
  1571. import {PopmotionPlugin, ThreeViewer} from 'threepipe'
  1572. const viewer = new ThreeViewer({...})
  1573. const cube = viewer.scene.getObjectByName('cube');
  1574. const popmotion = viewer.addPluginSync(new PopmotionPlugin())
  1575. // Move the object cube 1 unit up.
  1576. const anim = popmotion.animateTarget(cube, 'position', {
  1577. to: cube.position.clone().add(new Vector3(0,1,0)),
  1578. duration: 500, // ms
  1579. onComplete: () => isMovedUp = true,
  1580. onStop: () => throw(new Error('Animation stopped')),
  1581. })
  1582. // Alternatively, set the property directly in onUpdate.
  1583. const anim1 = popmotion.animate({
  1584. from: cube.position.y,
  1585. to: cube.position.y + 1,
  1586. duration: 500, // ms
  1587. onUpdate: (v) => {
  1588. cube.position.setY(v)
  1589. cube.setDirty()
  1590. },
  1591. onComplete: () => isMovedUp = true,
  1592. onStop: () => throw(new Error('Animation stopped')),
  1593. })
  1594. // await for animation. This promise will reject only if an exception is thrown in onStop
  1595. await anim.promise.catch((e)=>{
  1596. console.log(e, 'animation stopped before completion')
  1597. });
  1598. // or stop the animation
  1599. // anim.stop()
  1600. // Animate the color
  1601. await popmotion.animateAsync({ // Also await for the animation.
  1602. from: '#' + cube.material.color.getHexString(),
  1603. to: '#' + new Color().setHSL(Math.random(), 1, 0.5).getHexString(),
  1604. duration: 1000, // 1s
  1605. onUpdate: (v) => {
  1606. cube.material.color.set(v)
  1607. cube.material.setDirty()
  1608. },
  1609. })
  1610. ```
  1611. Note: The animation is started when the animate or animateAsync function is called.
  1612. ## CameraViewPlugin
  1613. [//]: # (todo: image)
  1614. Example: https://threepipe.org/examples/#camera-view-plugin/
  1615. Source Code: [src/plugins/animation/CameraViewPlugin.ts](./src/plugins/animation/CameraViewPlugin.ts)
  1616. API Reference: [CameraViewPlugin](https://threepipe.org/docs/classes/CameraViewPlugin.html)
  1617. CameraViewPlugin adds support to save and load camera views, which can then be animated to.
  1618. It uses PopmotionPlugin internally to animate any camera to a saved view or to loop through all the saved views.
  1619. It also provides a UI to manage the views.
  1620. ```typescript
  1621. import {CameraViewPlugin, ThreeViewer, CameraView, Vector3, Quaternion, EasingFunctions, timeout} from 'threepipe'
  1622. const viewer = new ThreeViewer({...})
  1623. const cameraViewPlugin = viewer.addPluginSync(new CameraViewPlugin())
  1624. const intialView = cameraViewPlugin.getView()
  1625. // or = viewer.scene.mainCamera.getView()
  1626. // create a new view
  1627. const view = new CameraView(
  1628. 'My View', // name
  1629. new Vector3(0, 0, 10), // position
  1630. new Vector3(0, 0, 0), // target
  1631. new Quaternion(0, 0, 0, 1), // quaternion rotation
  1632. 1 // zoom
  1633. )
  1634. // or clone a view
  1635. const view2 = intialView.clone()
  1636. view2.position.add(new Vector3(0, 5, 0)) // move up 5 units
  1637. // animate the main camera to a view
  1638. await cameraViewPlugin.animateToView(
  1639. view,
  1640. 2000, // in ms, = 2sec
  1641. EasingFunctions.easeInOut,
  1642. ).catch(()=>console.log('Animation stopped'))
  1643. // stop any/all animations
  1644. cameraViewPlugin.stopAllAnimations()
  1645. // add views to the plugin
  1646. cameraViewPlugin.addView(view)
  1647. cameraViewPlugin.addView(view2)
  1648. cameraViewPlugin.addView(intialView)
  1649. cameraViewPlugin.addCurrentView() // adds the current view of the main camera
  1650. // loop through all the views once
  1651. cameraViewPlugin.animDuration = 2000 // default duration
  1652. cameraViewPlugin.animEase = EasingFunctions.easeInOutSine // default easing
  1653. await cameraViewPlugin.animateAllViews()
  1654. // loop through all the views forever
  1655. cameraViewPlugin.viewLooping = true
  1656. await timeout(10000) // wait for some time
  1657. // stop looping
  1658. cameraViewPlugin.viewLooping = false
  1659. ```
  1660. ## RenderTargetPreviewPlugin
  1661. [//]: # (todo: image)
  1662. Example: https://threepipe.org/examples/#render-target-preview/
  1663. Source Code: [src/plugins/ui/RenderTargetPreviewPlugin.ts](./src/plugins/ui/RenderTargetPreviewPlugin.ts)
  1664. API Reference: [RenderTargetPreviewPlugin](https://threepipe.org/docs/classes/RenderTargetPreviewPlugin.html)
  1665. RenderTargetPreviewPlugin is a useful development and debugging plugin that renders any registered render-target to the screen in small collapsable panels.
  1666. ```typescript
  1667. import {ThreeViewer, RenderTargetPreviewPlugin, NormalBufferPlugin} from 'threepipe'
  1668. const viewer = new ThreeViewer({...})
  1669. const normalPlugin = viewer.addPluginSync(new NormalBufferPlugin(HalfFloatType))
  1670. const previewPlugin = viewer.addPluginSync(new RenderTargetPreviewPlugin())
  1671. // Show the normal buffer in a panel
  1672. previewPlugin.addTarget(()=>normalPlugin.target, 'normal', false, false)
  1673. ```
  1674. ## GeometryUVPreviewPlugin
  1675. [//]: # (todo: image)
  1676. Example: https://threepipe.org/examples/#geometry-uv-preview/
  1677. Source Code: [src/plugins/ui/GeometryUVPreviewPlugin.ts](./src/plugins/ui/GeometryUVPreviewPlugin.ts)
  1678. API Reference: [GeometryUVPreviewPlugin](https://threepipe.org/docs/classes/GeometryUVPreviewPlugin.html)
  1679. GeometryUVPreviewPlugin is a useful development and debugging plugin
  1680. that adds a panel to the viewer to show the UVs of a geometry.
  1681. ```typescript
  1682. import {ThreeViewer, GeometryUVPreviewPlugin, SphereGeometry} from 'threepipe'
  1683. const viewer = new ThreeViewer({...})
  1684. const previewPlugin = viewer.addPluginSync(new GeometryUVPreviewPlugin())
  1685. const geometry = new SphereGeometry(1, 32, 32)
  1686. // Show the normal buffer in a panel
  1687. previewPlugin.addGeometry(geometry, 'sphere')
  1688. ```
  1689. ## FrameFadePlugin
  1690. [//]: # (todo: image)
  1691. Example: https://threepipe.org/examples/#frame-fade-plugin/
  1692. Source Code: [src/plugins/pipeline/FrameFadePlugin.ts](./src/plugins/pipeline/FrameFadePlugin.ts)
  1693. API Reference: [FrameFadePlugin](https://threepipe.org/docs/classes/FrameFadePlugin.html)
  1694. FrameFadePlugin adds a post-render pass to the render manager and blends the last frame with the current frame over time. This is useful for creating smooth transitions between frames for example when changing the camera position, material, object properties, etc to avoid a sudden jump.
  1695. ```typescript
  1696. import {ThreeViewer, FrameFadePlugin} from 'threepipe'
  1697. const viewer = new ThreeViewer({...})
  1698. const fadePlugin = viewer.addPluginSync(new FrameFadePlugin())
  1699. // Make some changes in the scene (any visual change that needs to be faded)
  1700. // Start transition and wait for it to finish
  1701. await fadePlugin.startTransition(400) // duration in ms
  1702. ```
  1703. To stop a transition, call `fadePlugin.stopTransition()`. This will immediately set the current frame to the last frame and stop the transition. The transition is also automatically stopped when the camera is moved or some pointer event occurs on the canvas.
  1704. The plugin automatically tracks `setDirty()` function calls in objects, materials and the scene. It can be triggerred by calling `setDirty` on any material or object in the scene. Check the [example](https://threepipe.org/examples/#frame-fade-plugin/) for a demo. This can be disabled by options in the plugin.
  1705. ## VignettePlugin
  1706. [//]: # (todo: image)
  1707. Example: https://threepipe.org/examples/#vignette-plugin/
  1708. Source Code: [src/plugins/postprocessing/VignettePlugin.ts](./src/plugins/postprocessing/VignettePlugin.ts)
  1709. API Reference: [VignettePlugin](https://threepipe.org/docs/classes/VignettePlugin.html)
  1710. VignettePlugin adds a post-processing material extension to the ScreenPass in render manager
  1711. that applies a vignette effect to the final render. The parameters `power` and `color` can be changed to customize the effect.
  1712. ```typescript
  1713. import {ThreeViewer, VignettePlugin} from 'threepipe'
  1714. const viewer = new ThreeViewer({...})
  1715. const vignettePlugin = viewer.addPluginSync(VignettePlugin)
  1716. // Change the vignette color
  1717. vignettePlugin.power = 1
  1718. vignettePlugin.color = new Color(0.5, 0, 0)
  1719. // or
  1720. // vignettePlugin.color.set('#ff0000'); vignettePlugin.setDirty() // Call setDirty to tell the plugin that color has changed
  1721. ```
  1722. ## ChromaticAberrationPlugin
  1723. [//]: # (todo: image)
  1724. Example: https://threepipe.org/examples/#chromatic-aberration-plugin/
  1725. Source Code: [src/plugins/postprocessing/ChromaticAberrationPlugin.ts](./src/plugins/postprocessing/ChromaticAberrationPlugin.ts)
  1726. API Reference: [ChromaticAberrationPlugin](https://threepipe.org/docs/classes/ChromaticAberrationPlugin.html)
  1727. ChromaticAberrationPlugin adds a post-processing material extension to the ScreenPass in render manager
  1728. that applies a chromatic-aberration effect to the final render. The parameter `intensity` can be changed to customize the effect.
  1729. ```typescript
  1730. import {ThreeViewer, ChromaticAberrationPlugin} from 'threepipe'
  1731. const viewer = new ThreeViewer({...})
  1732. const chromaticAberrationPlugin = viewer.addPluginSync(ChromaticAberrationPlugin)
  1733. // Change the chromaticAberration color
  1734. chromaticAberrationPlugin.intensity = 0.5
  1735. ```
  1736. ## FilmicGrainPlugin
  1737. [//]: # (todo: image)
  1738. Example: https://threepipe.org/examples/#filmic-grain-plugin/
  1739. Source Code: [src/plugins/postprocessing/FilmicGrainPlugin.ts](./src/plugins/postprocessing/FilmicGrainPlugin.ts)
  1740. API Reference: [FilmicGrainPlugin](https://threepipe.org/docs/classes/FilmicGrainPlugin.html)
  1741. FilmicGrainPlugin adds a post-processing material extension to the ScreenPass in render manager
  1742. that applies a filmic-grain effect to the final render. The parameters `power` and `color` can be changed to customize the effect.
  1743. ```typescript
  1744. import {ThreeViewer, FilmicGrainPlugin} from 'threepipe'
  1745. const viewer = new ThreeViewer({...})
  1746. const filmicGrainPlugin = viewer.addPluginSync(FilmicGrainPlugin)
  1747. // Change the filmicGrain color
  1748. filmicGrainPlugin.intensity = 10
  1749. filmicGrainPlugin.multiply = false
  1750. ```
  1751. ## HDRiGroundPlugin
  1752. [//]: # (todo: image)
  1753. Example: https://threepipe.org/examples/#hdri-ground-plugin/
  1754. Source Code: [src/plugins/pipeline/HDRiGroundPlugin.ts](./src/plugins/extras/HDRiGroundPlugin.ts)
  1755. API Reference: [FrameFadePlugin](https://threepipe.org/docs/classes/HDRiGroundPlugin.html)
  1756. HDRiGroundPlugin patches the background shader in the renderer to add support for ground projected environment map/skybox. Works simply by setting the background same as the environemnt and enabling the plugin.
  1757. The world radius, tripod height, and origin position(center offset) can be set in the plugin.
  1758. The plugin is disabled by default when added. Set `.enabled` to enable it or pass `true` in the constructor.
  1759. If the background is not the same as the environment when enabled, the user will be prompted for this, unless `promptOnBackgroundMismatch` is set to `false` in the plugin.
  1760. ```typescript
  1761. import {ThreeViewer, FrameFadePlugin} from 'threepipe'
  1762. const viewer = new ThreeViewer({...})
  1763. const hdriGround = viewer.addPluginSync(new HDRiGrounPlugin())
  1764. // Load an hdr environment map
  1765. await viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  1766. // set background to environment
  1767. viewer.scene.background = 'environment'
  1768. // or
  1769. // viewer.scene.background = viewer.scene.environemnt
  1770. // enable the plugin
  1771. hdriGround.enabled = true
  1772. ```
  1773. Check the [example](https://threepipe.org/examples/#hdri-ground-plugin/) for a demo.
  1774. ## Rhino3dmLoadPlugin
  1775. Example: https://threepipe.org/examples/#rhino3dm-load/
  1776. Source Code: [src/plugins/import/Rhino3dmLoadPlugin.ts](./src/plugins/import/Rhino3dmLoadPlugin.ts)
  1777. API Reference: [Rhino3dmLoadPlugin](https://threepipe.org/docs/classes/Rhino3dmLoadPlugin.html)
  1778. Adds support for loading .3dm files generated by [Rhino 3D](https://www.rhino3d.com/). This plugin includes some changes with how 3dm files are loaded in three.js. The changes are around loading layer and primitive properties when set as reference in the 3dm files.
  1779. It also adds some helpful options to process the model after load.
  1780. ```typescript
  1781. import {Rhino3dmLoadPlugin} from 'threepipe'
  1782. const rhino3dmPlugin = viewer.addPluginSync(new Rhino3dmLoadPlugin())
  1783. rhino3dmPlugin.importMaterials = true // import materials source from 3dm file
  1784. rhino3dmPlugin.forceLayerMaterials = true // force material source to be layer in 3dm file.
  1785. rhino3dmPlugin.hideLineMesh = true // hide all lines and points in the model.
  1786. rhino3dmPlugin.replaceWithInstancedMesh = true // replace meshes with the same parent, geometry and material with a single instance mesh.
  1787. const mesh = await viewer.load('file.3dm')
  1788. ```
  1789. ## PLYLoadPlugin
  1790. Example: https://threepipe.org/examples/#ply-load/
  1791. Source Code: [src/plugins/import/PLYLoadPlugin.ts](./src/plugins/import/PLYLoadPlugin.ts)
  1792. API Reference: [PLYLoadPlugin](https://threepipe.org/docs/classes/PLYLoadPlugin.html)
  1793. Adds support for loading .ply ([Polygon file format](https://en.wikipedia.org/wiki/PLY_(file_format))) files.
  1794. ```typescript
  1795. import {PLYLoadPlugin} from 'threepipe'
  1796. viewer.addPluginSync(new PLYLoadPlugin())
  1797. const mesh = await viewer.load('file.ply')
  1798. ```
  1799. ## USDZLoadPlugin
  1800. Example: https://threepipe.org/examples/#usdz-load/
  1801. Source Code: [src/plugins/import/USDZLoadPlugin.ts](./src/plugins/import/USDZLoadPlugin.ts)
  1802. API Reference: [USDZLoadPlugin](https://threepipe.org/docs/classes/USDZLoadPlugin.html)
  1803. Adds support for loading .usdz and .usda ([Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html)) files.
  1804. ```typescript
  1805. import {USDZLoadPlugin} from 'threepipe'
  1806. viewer.addPluginSync(new USDZLoadPlugin())
  1807. const mesh = await viewer.load('file.usdz')
  1808. const mesh2 = await viewer.load('file.usda')
  1809. ```
  1810. ## STLLoadPlugin
  1811. Example: https://threepipe.org/examples/#stl-load/
  1812. Source Code: [src/plugins/import/STLLoadPlugin.ts](./src/plugins/import/STLLoadPlugin.ts)
  1813. API Reference: [STLLoadPlugin](https://threepipe.org/docs/classes/STLLoadPlugin.html)
  1814. Adds support for loading .stl ([Stereolithography](https://en.wikipedia.org/wiki/STL_(file_format))) files.
  1815. ```typescript
  1816. import {STLLoadPlugin} from 'threepipe'
  1817. viewer.addPluginSync(new STLLoadPlugin())
  1818. const mesh = await viewer.load('file.stl')
  1819. ```
  1820. ## KTX2LoadPlugin
  1821. Example: https://threepipe.org/examples/#ktx2-load/
  1822. Source Code: [src/plugins/import/KTX2LoadPlugin.ts](./src/plugins/import/KTX2LoadPlugin.ts)
  1823. API Reference: [KTX2LoadPlugin](https://threepipe.org/docs/classes/KTX2LoadPlugin.html)
  1824. Adds support for loading .ktx2 ([Khronos Texture](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) files.
  1825. KTX2LoadPlugin also adds support for exporting loaded .ktx2 files in glTF files with the [KHR_texture_basisu](https://www.khronos.org/registry/KHR/textures/2.0-extensions/KHR_texture_basisu/) extension.
  1826. ```typescript
  1827. import {KTX2LoadPlugin} from 'threepipe'
  1828. viewer.addPluginSync(new KTX2LoadPlugin())
  1829. const texture = await viewer.load('file.ktx2')
  1830. ```
  1831. ## KTXLoadPlugin
  1832. Example: https://threepipe.org/examples/#ktx-load/
  1833. Source Code: [src/plugins/import/KTXLoadPlugin.ts](./src/plugins/import/KTXLoadPlugin.ts)
  1834. API Reference: [KTXLoadPlugin](https://threepipe.org/docs/classes/KTXLoadPlugin.html)
  1835. Adds support for loading .ktx ([Khronos Texture](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) files.
  1836. Note: This plugin only adds support for loading .ktx file, and not exporting them in the bundled .glb. Use .ktx2 files instead of .ktx files for better compression and performance.
  1837. ```typescript
  1838. import {KTXLoadPlugin} from 'threepipe'
  1839. viewer.addPluginSync(new KTXLoadPlugin())
  1840. const texture = await viewer.load('file.ktx')
  1841. ```
  1842. # @threepipe Packages
  1843. Additional plugins can be found in the [plugins](plugins/) directory.
  1844. These add support for integrating with other libraries, adding new features, and other functionality with different licenses.
  1845. ## @threepipe/plugin-tweakpane
  1846. Tewakpane UI plugin for ThreePipe
  1847. [//]: # (todo: image)
  1848. Example: https://threepipe.org/examples/#viewer-uiconfig/
  1849. Source Code: [plugins/tweakpane/src/TweakpaneUiPlugin.ts](plugins/tweakpane/src/TweakpaneUiPlugin.ts)
  1850. API Reference: [TweakpaneUiPlugin](https://threepipe.org/plugins/tweakpane/docs/classes/TweakpaneUiPlugin.html)
  1851. NPM: `npm install @threepipe/plugin-tweakpane`
  1852. CDN: https://threepipe.org/plugins/tweakpane/dist/index.mjs
  1853. TweakpaneUiPlugin adds support for using [uiconfig-tweakpane](https://github.com/repalash/uiconfig-tweakpane)
  1854. to create a configuration UI in applications using the [Tweakpane](https://cocopon.github.io/tweakpane/) library.
  1855. The plugin takes the [uiconfig](https://github.com/repalash/uiconfig.js)
  1856. that's defined in the viewer and all the objects to automatically render a UI in the browser.
  1857. ```typescript
  1858. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  1859. import {TweakpaneUiPlugin} from '@threepipe/plugin-tweakpane'
  1860. const viewer = new ThreeViewer({...})
  1861. // Add the plugin
  1862. const plugin = viewer.addPluginSync(new TweakpaneUiPlugin(true)) // true to show expanded the UI by default
  1863. // Add the UI for the viewer
  1864. plugin.appendChild(viewer.uiConfig)
  1865. // Add UI for some plugins
  1866. plugin.setupPlugins(TonemapPlugin, DropzonePlugin)
  1867. ```
  1868. ## @threepipe/plugin-tweakpane-editor
  1869. Tweakpane Editor Plugin for ThreePipe
  1870. [//]: # (todo: image)
  1871. Example: https://threepipe.org/examples/#tweakpane-editor/
  1872. Source Code: [plugins/tweakpane-editor/src/TweakpaneEditorPlugin.ts](plugins/tweakpane-editor/src/TweakpaneEditorPlugin.ts)
  1873. API Reference: [TweakpaneEditorPlugin](https://threepipe.org/plugins/tweakpane-editor/docs/classes/TweakpaneEditorPlugin.html)
  1874. NPM: `npm install @threepipe/plugin-tweakpane-editor`
  1875. CDN: https://threepipe.org/plugins/tweakpane-editor/dist/index.mjs
  1876. TweakpaneEditorPlugin uses TweakpaneUiPlugin to create an editor for editing viewer,
  1877. plugins, model and material configurations in the browser.
  1878. ```typescript
  1879. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  1880. import {TweakpaneEditorPlugin} from '@threepipe/plugin-tweakpane-editor'
  1881. const viewer = new ThreeViewer({...})
  1882. viewer.addPluginSync(new TweakpaneUiPlugin(true))
  1883. const editor = viewer.addPluginSync(new TweakpaneEditorPlugin())
  1884. // Add some plugins to the viewer
  1885. await viewer.addPlugins([
  1886. new ViewerUiConfigPlugin(),
  1887. // new SceneUiConfigPlugin(), // this is already in ViewerUiPlugin
  1888. new DepthBufferPlugin(HalfFloatType, true, true),
  1889. new NormalBufferPlugin(HalfFloatType, false),
  1890. new RenderTargetPreviewPlugin(false),
  1891. ])
  1892. // Load the plugin UI in the editor and tweakpane ui with categories.
  1893. editor.loadPlugins({
  1894. ['Viewer']: [ViewerUiConfigPlugin, SceneUiConfigPlugin, DropzonePlugin, FullScreenPlugin],
  1895. ['GBuffer']: [DepthBufferPlugin, NormalBufferPlugin],
  1896. ['Post-processing']: [TonemapPlugin],
  1897. ['Debug']: [RenderTargetPreviewPlugin],
  1898. })
  1899. ```
  1900. ## @threepipe/plugin-extra-importers
  1901. Exports several plugins to add support for various file types.
  1902. Example: https://threepipe.org/examples/#extra-importer-plugins/
  1903. Source Code: [plugins/extra-importers/src/index.ts](plugins/extra-importers/src/index.ts)
  1904. API Reference: [@threepipe/plugin-extra-importers](https://threepipe.org/plugins/extra-importers/docs)
  1905. NPM: `npm install @threepipe/plugin-extra-importers`
  1906. CDN: https://threepipe.org/plugins/extra-importers/dist/index.mjs
  1907. This package exports several plugins to add support for several file types using the following plugins
  1908. - [TDSLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/TDSLoadPlugin.html) - Load 3DS Max (.3ds) files
  1909. - [ThreeMFLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/ThreeMFLoadPlugin.html) - Load 3MF (.3mf) files
  1910. - [ColladaLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/ColladaLoadPlugin.html) - Load Collada (.dae) files
  1911. - [AMFLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/AMFLoadPlugin.html) - Load AMF (.amf) files
  1912. - [BVHLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/BVHLoadPlugin.html) - Load BVH (.bvh) files
  1913. - [VOXLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VOXLoadPlugin.html) - Load MagicaVoxel (.vox) files
  1914. - [GCodeLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/GCodeLoadPlugin.html) - Load GCode (.gcode) files
  1915. - [MDDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/MDDLoadPlugin.html) - Load MDD (.mdd) files
  1916. - [PCDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/PCDLoadPlugin.html) - Load Point cloud data (.pcd) files
  1917. - [TiltLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/TiltLoadPlugin.html) - Load Tilt Brush (.tilt) files
  1918. - [VRMLLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VRMLLoadPlugin.html) - Load VRML (.wrl) files
  1919. - [MPDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/MPDLoadPlugin.html) - Load LDraw (.mpd) files
  1920. - [VTKLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VTKLoadPlugin.html) - Load VTK (.vtk) files
  1921. - [XYZLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/XYZLoadPlugin.html) - Load XYZ (.xyz) files
  1922. To add all the plugins at once use `extraImporters`. This adds support for loading all the above file types.
  1923. ```typescript
  1924. import {ThreeViewer} from 'threepipe'
  1925. import {extraImporters} from '@threepipe/plugin-extra-importers'
  1926. const viewer = new ThreeViewer({...})
  1927. viewer.addPluginsSync(extraImporters)
  1928. // Now load any file as is.
  1929. const model = await viewer.load<IObject3D>('file.3mf')
  1930. // To load the file as a data url, use the correct mimetype
  1931. const model1 = await viewer.load<IObject3D>('data:model/3mf;base64,...')
  1932. ```
  1933. Remove the `<IObject3D>` if using javascript and not typescript.
  1934. ## @threepipe/plugin-blend-importer
  1935. Exports [BlendImporterPlugin](https://threepipe.org/plugins/blend-importer/docs/classes/BlendLoadPlugin.html) which adds support for loading .blend files.
  1936. It uses [js.blend](https://github.com/acweathersby/js.blend) for parsing blend file structure.
  1937. Note: This is still a WIP.
  1938. Currently working: `Mesh`, `BufferGeometry` and basic `PointLight`.
  1939. To be added: `PhysicalMaterial`, `UnlitMaterial` (similar to blender-gltf-io plugin)
  1940. Example: https://threepipe.org/examples/#blend-load/
  1941. Source Code: [plugins/blend-importer/src/index.ts](plugins/blend-importer/src/index.ts)
  1942. API Reference: [@threepipe/plugin-blend-importer](https://threepipe.org/plugins/blend-importer/docs)
  1943. NPM: `npm install @threepipe/plugin-blend-importer`
  1944. ```typescript
  1945. import {ThreeViewer} from 'threepipe'
  1946. import {BlendLoadPlugin} from '@threepipe/plugin-blend-importer'
  1947. const viewer = new ThreeViewer({...})
  1948. viewer.addPluginSync(BlendLoadPlugin)
  1949. // Now load any .blend file.
  1950. const model = await viewer.load<IObject3D>('path/to/file.blend')
  1951. // To load the file as a data url, use the correct mimetype
  1952. const model1 = await viewer.load<IObject3D>('data:application/x-blender;base64,...')
  1953. ```
  1954. [//]: # ( TODO: The plugin should parse and references to other assets and find them relative to the .blend file or the current location.)