2

i'm new to three.js so i apologize if this question has been asked before. i have this external .txt file that contains the x, y, z positions of 256 atoms. the first lines of the .txt file goes as follows:

256
1 0.702825 2.71217 2.71612
1 16.9592 2.64886 6.79019
1 0.681418 2.68359 10.8911
...

the first row contains the number of atoms in the compound and the first column, the size of the atom. the remaining values are the x, y, z values for every respective atom. so far i added the first atom by manually inputting the position:

...
scene.add(sphere); 
sphere.position.set(0.702825, 2.71217, 2.71612);

can i open and read the .txt file line by line to store the next position in x, y and z variables? what can i do to use the external file's information?

Yujia Ding
  • 65
  • 5

2 Answers2

1
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19
1

Use the fetch API:

fetch('myfile.txt').then(response => response.text()).then(text => {
  const atoms = text.split('\n')  // split into lines
    .map(line => line.trim())     // remove whitespace at the beginning and end
    .slice(1)                     // remove the first line
    .map(line => line
      .split(' ')                 // split by ' '
      .map(Number))               // and parse the parts to numbers
    .map(([size, x, y, z]) => ({ size, x, y, z })); // create objects from the arrays
});

atoms should now contain something like this:

[
  { size: 1, x: 0.702825, y: 2.71217, z: 2.71612 },
  { size: 1, x: 16.9592, y: 2.64886, z: 6.79019 },
  ...
]

I'm sure you can figure out how to use that in Three.js.

Looping through the atoms could look like this:

atoms.forEach(({ x, y, z }) => { // using destructuring
  // ...
  sphere.position.set(x, y, z);
  // ...
});

or:

atoms.forEach(atom => { // normal forEach-loop
  // ...
  sphere.position.set(atom.x, atom.y, atom.z);
  // ...
});

or:

for (let i = 0, len = atoms.length; i < len; i++) { // normal for-loop
  // ...
  sphere.position.set(atoms[i].x, atoms[i].y, atoms[i].z);
  // ...
}

Of course, you can use XMLHttpRequest instead of the fetch API.

PeterMader
  • 6,987
  • 1
  • 21
  • 31