threepipe
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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