css3d_molecules.html 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>three.js css3d - molecules</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. background-color: #050505;
  11. background: radial-gradient(ellipse at center, rgba(43,45,48,1) 0%,rgba(0,0,0,1) 100%);
  12. }
  13. .bond {
  14. width: 5px;
  15. height: 10px;
  16. background: #eee;
  17. display: block;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div id="container"></div>
  23. <div id="info"><a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> css3d - molecules</div>
  24. <!-- Import maps polyfill -->
  25. <!-- Remove this when import maps will be widely supported -->
  26. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  27. <script type="importmap">
  28. {
  29. "imports": {
  30. "three": "../build/three.module.js",
  31. "three/addons/": "./jsm/"
  32. }
  33. }
  34. </script>
  35. <script type="module">
  36. import * as THREE from 'three';
  37. import { TrackballControls } from 'three/addons/controls/TrackballControls.js';
  38. import { PDBLoader } from 'three/addons/loaders/PDBLoader.js';
  39. import { CSS3DRenderer, CSS3DObject, CSS3DSprite } from 'three/addons/renderers/CSS3DRenderer.js';
  40. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  41. let camera, scene, renderer;
  42. let controls;
  43. let root;
  44. const objects = [];
  45. const tmpVec1 = new THREE.Vector3();
  46. const tmpVec2 = new THREE.Vector3();
  47. const tmpVec3 = new THREE.Vector3();
  48. const tmpVec4 = new THREE.Vector3();
  49. const offset = new THREE.Vector3();
  50. const VIZ_TYPE = {
  51. 'Atoms': 0,
  52. 'Bonds': 1,
  53. 'Atoms + Bonds': 2
  54. };
  55. const MOLECULES = {
  56. 'Ethanol': 'ethanol.pdb',
  57. 'Aspirin': 'aspirin.pdb',
  58. 'Caffeine': 'caffeine.pdb',
  59. 'Nicotine': 'nicotine.pdb',
  60. 'LSD': 'lsd.pdb',
  61. 'Cocaine': 'cocaine.pdb',
  62. 'Cholesterol': 'cholesterol.pdb',
  63. 'Lycopene': 'lycopene.pdb',
  64. 'Glucose': 'glucose.pdb',
  65. 'Aluminium oxide': 'Al2O3.pdb',
  66. 'Cubane': 'cubane.pdb',
  67. 'Copper': 'cu.pdb',
  68. 'Fluorite': 'caf2.pdb',
  69. 'Salt': 'nacl.pdb',
  70. 'YBCO superconductor': 'ybco.pdb',
  71. 'Buckyball': 'buckyball.pdb',
  72. // 'Diamond': 'diamond.pdb',
  73. 'Graphite': 'graphite.pdb'
  74. };
  75. const params = {
  76. vizType: 2,
  77. molecule: 'caffeine.pdb'
  78. };
  79. const loader = new PDBLoader();
  80. const colorSpriteMap = {};
  81. const baseSprite = document.createElement( 'img' );
  82. init();
  83. animate();
  84. function init() {
  85. camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 5000 );
  86. camera.position.z = 1000;
  87. scene = new THREE.Scene();
  88. root = new THREE.Object3D();
  89. scene.add( root );
  90. //
  91. renderer = new CSS3DRenderer();
  92. renderer.setSize( window.innerWidth, window.innerHeight );
  93. document.getElementById( 'container' ).appendChild( renderer.domElement );
  94. //
  95. controls = new TrackballControls( camera, renderer.domElement );
  96. controls.rotateSpeed = 0.5;
  97. //
  98. baseSprite.onload = function () {
  99. loadMolecule( params.molecule );
  100. };
  101. baseSprite.src = 'textures/sprites/ball.png';
  102. //
  103. window.addEventListener( 'resize', onWindowResize );
  104. //
  105. const gui = new GUI();
  106. gui.add( params, 'vizType', VIZ_TYPE ).onChange( changeVizType );
  107. gui.add( params, 'molecule', MOLECULES ).onChange( loadMolecule );
  108. gui.open();
  109. }
  110. function changeVizType( value ) {
  111. if ( value === 0 ) showAtoms();
  112. else if ( value === 1 ) showBonds();
  113. else showAtomsBonds();
  114. }
  115. //
  116. function showAtoms() {
  117. for ( let i = 0; i < objects.length; i ++ ) {
  118. const object = objects[ i ];
  119. if ( object instanceof CSS3DSprite ) {
  120. object.element.style.display = '';
  121. object.visible = true;
  122. } else {
  123. object.element.style.display = 'none';
  124. object.visible = false;
  125. }
  126. }
  127. }
  128. function showBonds() {
  129. for ( let i = 0; i < objects.length; i ++ ) {
  130. const object = objects[ i ];
  131. if ( object instanceof CSS3DSprite ) {
  132. object.element.style.display = 'none';
  133. object.visible = false;
  134. } else {
  135. object.element.style.display = '';
  136. object.element.style.height = object.userData.bondLengthFull;
  137. object.visible = true;
  138. }
  139. }
  140. }
  141. function showAtomsBonds() {
  142. for ( let i = 0; i < objects.length; i ++ ) {
  143. const object = objects[ i ];
  144. object.element.style.display = '';
  145. object.visible = true;
  146. if ( ! ( object instanceof CSS3DSprite ) ) {
  147. object.element.style.height = object.userData.bondLengthShort;
  148. }
  149. }
  150. }
  151. //
  152. function colorify( ctx, width, height, color ) {
  153. const r = color.r, g = color.g, b = color.b;
  154. const imageData = ctx.getImageData( 0, 0, width, height );
  155. const data = imageData.data;
  156. for ( let i = 0, l = data.length; i < l; i += 4 ) {
  157. data[ i + 0 ] *= r;
  158. data[ i + 1 ] *= g;
  159. data[ i + 2 ] *= b;
  160. }
  161. ctx.putImageData( imageData, 0, 0 );
  162. }
  163. function imageToCanvas( image ) {
  164. const width = image.width;
  165. const height = image.height;
  166. const canvas = document.createElement( 'canvas' );
  167. canvas.width = width;
  168. canvas.height = height;
  169. const context = canvas.getContext( '2d' );
  170. context.drawImage( image, 0, 0, width, height );
  171. return canvas;
  172. }
  173. //
  174. function loadMolecule( model ) {
  175. const url = 'models/pdb/' + model;
  176. for ( let i = 0; i < objects.length; i ++ ) {
  177. const object = objects[ i ];
  178. object.parent.remove( object );
  179. }
  180. objects.length = 0;
  181. loader.load( url, function ( pdb ) {
  182. const geometryAtoms = pdb.geometryAtoms;
  183. const geometryBonds = pdb.geometryBonds;
  184. const json = pdb.json;
  185. geometryAtoms.computeBoundingBox();
  186. geometryAtoms.boundingBox.getCenter( offset ).negate();
  187. geometryAtoms.translate( offset.x, offset.y, offset.z );
  188. geometryBonds.translate( offset.x, offset.y, offset.z );
  189. const positionAtoms = geometryAtoms.getAttribute( 'position' );
  190. const colorAtoms = geometryAtoms.getAttribute( 'color' );
  191. const position = new THREE.Vector3();
  192. const color = new THREE.Color();
  193. for ( let i = 0; i < positionAtoms.count; i ++ ) {
  194. position.fromBufferAttribute( positionAtoms, i );
  195. color.fromBufferAttribute( colorAtoms, i );
  196. const atomJSON = json.atoms[ i ];
  197. const element = atomJSON[ 4 ];
  198. if ( ! colorSpriteMap[ element ] ) {
  199. const canvas = imageToCanvas( baseSprite );
  200. const context = canvas.getContext( '2d' );
  201. colorify( context, canvas.width, canvas.height, color );
  202. const dataUrl = canvas.toDataURL();
  203. colorSpriteMap[ element ] = dataUrl;
  204. }
  205. const colorSprite = colorSpriteMap[ element ];
  206. const atom = document.createElement( 'img' );
  207. atom.src = colorSprite;
  208. const object = new CSS3DSprite( atom );
  209. object.position.copy( position );
  210. object.position.multiplyScalar( 75 );
  211. object.matrixAutoUpdate = false;
  212. object.updateMatrix();
  213. root.add( object );
  214. objects.push( object );
  215. }
  216. const positionBonds = geometryBonds.getAttribute( 'position' );
  217. const start = new THREE.Vector3();
  218. const end = new THREE.Vector3();
  219. for ( let i = 0; i < positionBonds.count; i += 2 ) {
  220. start.fromBufferAttribute( positionBonds, i );
  221. end.fromBufferAttribute( positionBonds, i + 1 );
  222. start.multiplyScalar( 75 );
  223. end.multiplyScalar( 75 );
  224. tmpVec1.subVectors( end, start );
  225. const bondLength = tmpVec1.length() - 50;
  226. //
  227. let bond = document.createElement( 'div' );
  228. bond.className = 'bond';
  229. bond.style.height = bondLength + 'px';
  230. let object = new CSS3DObject( bond );
  231. object.position.copy( start );
  232. object.position.lerp( end, 0.5 );
  233. object.userData.bondLengthShort = bondLength + 'px';
  234. object.userData.bondLengthFull = ( bondLength + 55 ) + 'px';
  235. //
  236. const axis = tmpVec2.set( 0, 1, 0 ).cross( tmpVec1 );
  237. const radians = Math.acos( tmpVec3.set( 0, 1, 0 ).dot( tmpVec4.copy( tmpVec1 ).normalize() ) );
  238. const objMatrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  239. object.matrix.copy( objMatrix );
  240. object.quaternion.setFromRotationMatrix( object.matrix );
  241. object.matrixAutoUpdate = false;
  242. object.updateMatrix();
  243. root.add( object );
  244. objects.push( object );
  245. //
  246. bond = document.createElement( 'div' );
  247. bond.className = 'bond';
  248. bond.style.height = bondLength + 'px';
  249. const joint = new THREE.Object3D( bond );
  250. joint.position.copy( start );
  251. joint.position.lerp( end, 0.5 );
  252. joint.matrix.copy( objMatrix );
  253. joint.quaternion.setFromRotationMatrix( joint.matrix );
  254. joint.matrixAutoUpdate = false;
  255. joint.updateMatrix();
  256. object = new CSS3DObject( bond );
  257. object.rotation.y = Math.PI / 2;
  258. object.matrixAutoUpdate = false;
  259. object.updateMatrix();
  260. object.userData.bondLengthShort = bondLength + 'px';
  261. object.userData.bondLengthFull = ( bondLength + 55 ) + 'px';
  262. object.userData.joint = joint;
  263. joint.add( object );
  264. root.add( joint );
  265. objects.push( object );
  266. }
  267. //console.log( "CSS3DObjects:", objects.length );
  268. changeVizType( params.vizType );
  269. } );
  270. }
  271. //
  272. function onWindowResize() {
  273. camera.aspect = window.innerWidth / window.innerHeight;
  274. camera.updateProjectionMatrix();
  275. renderer.setSize( window.innerWidth, window.innerHeight );
  276. }
  277. function animate() {
  278. requestAnimationFrame( animate );
  279. controls.update();
  280. const time = Date.now() * 0.0004;
  281. root.rotation.x = time;
  282. root.rotation.y = time * 0.7;
  283. render();
  284. }
  285. function render() {
  286. renderer.render( scene, camera );
  287. }
  288. </script>
  289. </body>
  290. </html>