threepipe
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

script.ts 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import {
  2. _testFinish,
  3. BaseGroundPlugin,
  4. BasicShadowMap,
  5. Color,
  6. DataUtils,
  7. DirectionalLight,
  8. IObject3D,
  9. MaterialExtension,
  10. ProgressivePlugin,
  11. ShaderChunk,
  12. shaderReplaceString,
  13. SSAAPlugin,
  14. ThreeViewer,
  15. Vector3,
  16. } from 'threepipe'
  17. import {TweakpaneUiPlugin} from '@threepipe/plugin-tweakpane'
  18. const hdris = [
  19. 'https://threejs.org/examples/textures/equirectangular/quarry_01_1k.hdr',
  20. 'https://threejs.org/examples/textures/equirectangular/spot1Lux.hdr',
  21. 'https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr',
  22. 'https://dist.pixotronics.com/webgi/assets/hdr/gem_2.hdr',
  23. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_04_1k.hdr',
  24. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_03_1k.hdr',
  25. 'https://threejs.org/examples/textures/equirectangular/pedestrian_overpass_1k.hdr',
  26. 'https://threejs.org/examples/textures/equirectangular/blouberg_sunrise_2_1k.hdr',
  27. 'https://threejs.org/examples/textures/equirectangular/royal_esplanade_1k.hdr',
  28. 'https://threejs.org/examples/textures/equirectangular/moonless_golf_1k.hdr',
  29. 'https://threejs.org/examples/textures/equirectangular/san_giuseppe_bridge_2k.hdr',
  30. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_06_1k.hdr',
  31. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_05_1k.hdr',
  32. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_02_1k.hdr',
  33. 'https://hdrihaven.r2cache.com/hdr/1k/studio_small_01_1k.hdr',
  34. ]
  35. async function init() {
  36. const viewer = new ThreeViewer({
  37. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  38. msaa: false,
  39. rgbm: false,
  40. plugins: [new ProgressivePlugin((window as any).TESTING ? 20 : 200), SSAAPlugin],
  41. dropzone: {
  42. addOptions: {
  43. disposeSceneObjects: true,
  44. autoSetEnvironment: true,
  45. autoSetBackground: true,
  46. },
  47. },
  48. })
  49. const directionalLight = createDirLight(viewer)
  50. viewer.materialManager.registerMaterialExtension(extension)
  51. viewer.renderManager.renderer.shadowMap.type = BasicShadowMap
  52. // extra check to ignore the sampling of shadow if intensity is 0
  53. ShaderChunk.lights_fragment_begin = shaderReplaceString(
  54. ShaderChunk.lights_fragment_begin,
  55. 'directLight.color *= ( directLight.visible && receiveShadow )',
  56. 'directLight.color *= ( directLight.visible && receiveShadow && length(directLight.color) > 0.001)',
  57. {replaceAll: true})
  58. const ground = viewer.addPluginSync(BaseGroundPlugin)
  59. ground.mesh!.castShadow = false
  60. ground.material!.roughness = 1
  61. ground.material!.metalness = 0
  62. const ui = viewer.addPluginSync(new TweakpaneUiPlugin(false))
  63. await viewer.load<IObject3D>('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  64. autoCenter: true,
  65. autoScale: true,
  66. })
  67. viewer.scene.envMapIntensity = 1
  68. await viewer.setEnvironmentMap(hdris[0], {
  69. setBackground: true,
  70. })
  71. ui.appendChild({
  72. type: 'dropdown',
  73. label: 'Environment Map',
  74. children: hdris.map((url)=>({
  75. label: url.split('/').pop()!.split('.').shift()!,
  76. value: url,
  77. })),
  78. value: hdris[0],
  79. onChange: async(ev)=>{
  80. console.log(ev.value)
  81. await viewer.setEnvironmentMap(ev.value, {
  82. setBackground: true,
  83. })
  84. refreshHist()
  85. },
  86. })
  87. let histogram2 = createHistogramFromImage(viewer.scene.environment?.image)
  88. function refreshHist() {
  89. histogram2 = createHistogramFromImage(viewer.scene.environment?.image)
  90. }
  91. viewer.addEventListener('postFrame', ()=>updateLight(viewer, directionalLight, histogram2))
  92. ui.setupPluginUi(BaseGroundPlugin)
  93. // const targetPreview = viewer.addPluginSync(new RenderTargetPreviewPlugin())
  94. // targetPreview.addTarget(()=>directionalLight.shadow.map, 'shadow')
  95. }
  96. const extension: MaterialExtension = {
  97. isCompatible: ()=> true,
  98. computeCacheKey: ()=> 'aomap1',
  99. shaderExtender(shader) {
  100. shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#include <aomap_fragment>', `
  101. #ifdef USE_AOMAP
  102. // reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture
  103. float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
  104. #else
  105. const int ii = 0;
  106. DirectionalLightShadow edls = directionalLightShadows[ ii ];
  107. float ambientOcclusion = getShadow( directionalShadowMap[ ii ], edls.shadowMapSize, edls.shadowBias, edls.shadowRadius, vDirectionalShadowCoord[ ii ] );
  108. #endif
  109. reflectedLight.indirectDiffuse *= ambientOcclusion;
  110. #if defined( USE_ENVMAP ) && defined( STANDARD )
  111. float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );
  112. reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
  113. #endif
  114. `)
  115. // shader.defines.USE_UV = ''
  116. },
  117. }
  118. function createDirLight(viewer: ThreeViewer) {
  119. const directionalLight = new DirectionalLight(0xffffff, 4)
  120. directionalLight.position.set(-2, -2, 2)
  121. directionalLight.lookAt(0, 0, 0)
  122. directionalLight.color.set(0xffffff)
  123. directionalLight.intensity = 0
  124. directionalLight.castShadow = true
  125. directionalLight.shadow.mapSize.setScalar(1024)
  126. directionalLight.shadow.camera.near = 0.1
  127. directionalLight.shadow.camera.far = 10
  128. directionalLight.shadow.camera.top = 2
  129. directionalLight.shadow.camera.bottom = -2
  130. directionalLight.shadow.camera.left = -2
  131. directionalLight.shadow.camera.right = 2
  132. viewer.scene.addObject(directionalLight, {addToRoot: true})
  133. // move to index 0 in parent.children, so that directionalLight always has index 0 in shader. required for material extension
  134. const parent = directionalLight.parent!
  135. const index = parent.children.indexOf(directionalLight)
  136. if (index > 0) {
  137. parent.children.splice(index, 1)
  138. parent.children.unshift(directionalLight)
  139. }
  140. return directionalLight
  141. }
  142. function updateLight(viewer: ThreeViewer, directionalLight: DirectionalLight, histogram: ReturnType<typeof createHistogramFromImage>) {
  143. if (viewer.renderManager.frameCount < 1) return
  144. // if (viewer.renderManager.frameCount > 2) return
  145. const bounds = viewer.scene.getBounds(false)
  146. const size = bounds.getSize(new Vector3()).length()
  147. const center = bounds.getCenter(new Vector3())
  148. const i = viewer.renderManager.frameCount <= 1 ? histogram.brightestI : histogram.sampleIndex()
  149. histogram.indexToColor(i, directionalLight)
  150. directionalLight.intensity = 0 // so it doesnt show in the scene
  151. histogram.indexToPosition(i, directionalLight.position).multiplyScalar(0.5 + size).add(center)
  152. directionalLight.lookAt(center)
  153. directionalLight.shadow.camera.near = Math.max(size / 100, 0.1)
  154. directionalLight.shadow.camera.far = size * 2.5
  155. directionalLight.shadow.camera.updateProjectionMatrix()
  156. viewer.renderManager.resetShadows()
  157. }
  158. function sampleRandom2(pow = 2) {
  159. return Math.max(0, Math.pow(Math.random(), pow) - 0.001)
  160. }
  161. function sampleRandom() {
  162. return Math.max(0, Math.random() - 0.001)
  163. }
  164. const maxIntensityClamp = 50
  165. const ignoreBottomBins = 1 // should be at-least 1 to ignore black pixels.
  166. const numBins = 100 // Number of bins in the histogram (configurable)
  167. const sampleRandPower = 1.25 // increase this to give more focus to higher intensity pixels. between 1 and 2
  168. const topHalf = true // todo if this is true, half the shadow in shader?
  169. function createHistogramFromImage(image: {data: Uint16Array, width: number, height: number}) {
  170. const histogram: number[][] = []
  171. let maxIntensity = -1
  172. let brightestI = 0
  173. // const maxIntensity1 = 65504
  174. for (let i = 0; i < image.data.length / 4; i++) {
  175. const r = DataUtils.fromHalfFloat(image.data[i * 4])
  176. const g = DataUtils.fromHalfFloat(image.data[i * 4 + 1])
  177. const b = DataUtils.fromHalfFloat(image.data[i * 4 + 2])
  178. const a = DataUtils.fromHalfFloat(image.data[i * 4 + 3])
  179. const intensity = a * Math.max(r, g, b) // Calculate intensity
  180. const binIndex = Math.floor(numBins * Math.max(0, Math.min(1 - 0.001, intensity / maxIntensityClamp))) // Calculate the bin index
  181. histogram[binIndex] ||= []
  182. histogram[binIndex].push(i)
  183. if (maxIntensity < intensity) {
  184. maxIntensity = intensity
  185. brightestI = i
  186. }
  187. if (topHalf && i > image.data.length / 8) break
  188. }
  189. histogram.reverse()
  190. const cdf = histogram.map((bin) => bin ? bin.length : 0)
  191. const maxW = numBins - 1 - ignoreBottomBins + 1
  192. cdf[0] = cdf[0] * maxW
  193. for (let i = 1; i < numBins; i++) {
  194. cdf[i] = cdf[i - 1] + (cdf[i] || 0) * (maxW - i) // *i for intensity of that bin
  195. }
  196. console.log(cdf)
  197. return {
  198. histogram, cdf,
  199. brightestI,
  200. maxIntensity,
  201. sampleIndex: ()=>{
  202. const max = cdf[cdf.length - 1]
  203. const r = sampleRandom2(sampleRandPower) * max
  204. const binIndex = cdf.findIndex((value) => value >= r)
  205. const bin = histogram[binIndex]
  206. const index = Math.floor(bin.length * sampleRandom())
  207. return bin[index]
  208. },
  209. indexToPosition: (i: number, position: Vector3)=>{
  210. // todo handle envMapRotation
  211. const {width, height} = image
  212. const x = i % width / width
  213. const y = 1 - Math.floor(i / width) / height
  214. const phi = Math.PI * (x * 2 - 1)
  215. const theta = Math.PI * 0.5 * (y * 2 - 1)
  216. return position.set(
  217. Math.cos(theta) * Math.cos(phi),
  218. Math.sin(theta),
  219. Math.cos(theta) * Math.sin(phi),
  220. )
  221. },
  222. indexToColor: (i: number, light: {color: Color, intensity: number})=>{
  223. // todo handle envMapIntensity
  224. const r = DataUtils.fromHalfFloat(image.data[i * 4])
  225. const g = DataUtils.fromHalfFloat(image.data[i * 4 + 1])
  226. const b = DataUtils.fromHalfFloat(image.data[i * 4 + 2])
  227. const a = DataUtils.fromHalfFloat(image.data[i * 4 + 3])
  228. light.color.setRGB(Math.min(1, r * a), Math.min(1, g * a), Math.min(1, b * a))
  229. light.intensity = Math.min(a * Math.max(r, g, b), maxIntensityClamp)
  230. },
  231. }
  232. }
  233. init().finally(_testFinish)