atomsGL.cpp 28 KB
Newer Older
1
/*
2
# Copyright 2016-2018 Ruben Jesus Garcia Hernandez
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
 #
 #     http://www.apache.org/licenses/LICENSE-2.0
 #
 # Unless required by applicable law or agreed to in writing, software
 # distributed under the License is distributed on an "AS IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
*/


18
19
20
21
22
#include <math.h>

#include "eprintf.h"
#include "TessShaders.h"
#include "UnitCellShaders.h"
23
#include "markerShaders.h"
24
25
26
27
28
#include "atomsGL.h"
#include "atoms.hpp"
#include "ConfigFile.h"
#include "CompileGLShader.h"
#include "polyhedron.h"
29
#include "Grid.h"
30
31
32
33

GLenum atomTexture(GLuint t)
{
	GLenum e;
34
	int finalatoms=getTotalAtomsInTexture();
35
	//rgh: scale atoms here
36
	//in google cardboard, this is called again if the program is running, so leave original or atoms get progresivelly smaller!
37
38
	float *a=new float[finalatoms*4];
	for (int i = 0; i < atomsInPeriodicTable; i++) {
39
40
41
42
43
		a[i*4+0]=atomColours[i][0];
		a[i*4+1]=atomColours[i][1];
		a[i*4+2]=atomColours[i][2];
		a[i*4+3]=atomColours[i][3] * atomScaling;
	}
44
45
46
47
48
49
	for (int i=0;i<extraAtomNames.size();i++) {
		a[(i+atomsInPeriodicTable)*4+0]=extraAtomData[i][0];
		a[(i+atomsInPeriodicTable)*4+1]=extraAtomData[i][1];
		a[(i+atomsInPeriodicTable)*4+2]=extraAtomData[i][2];
		a[(i+atomsInPeriodicTable)*4+3]=extraAtomData[i][3]*atomScaling;
	}
50
	glBindTexture(GL_TEXTURE_2D, t); //atom texture
51
52
53
	if ((e = glGetError()) != GL_NO_ERROR) {
		eprintf("opengl error %d, atomTexture bind\n", e);
	}
54
55
56
57
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
58
59
60
	if ((e = glGetError()) != GL_NO_ERROR) {
		eprintf("opengl error %d, atomTexture parameter\n", e);
	}
61
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, finalatoms, 1, 0, GL_RGBA, GL_FLOAT, a);
62
63
64
	if ((e = glGetError()) != GL_NO_ERROR) {
		eprintf("opengl error %d, atomTexture glTexImage2D\n", e);
	}
65
66
	glBindTexture( GL_TEXTURE_2D, 0 );
	if ((e = glGetError()) != GL_NO_ERROR) {
67
		eprintf("opengl error %d, atomTexture\n", e);
68
	}
69
	delete [] a;
70
71
72
73
74
75
	return e;
}

//WARNING: This should be called after SetupAtoms
//This means that numAtoms now has the cummulative distribution!
//This should be called after the atom texture is prepared, and therefore has the atomscaling pre-multiplied
76
GLenum SetupAtomsNoTess (GLuint **AtomVAO /*[4]*/, GLuint **AtomVertBuffer/*[3]*/, GLuint **AtomIndexBuffer/*[2]*/)
77
78
	//atoms, cloned atoms
	//rgh: FIXME: add AtomVAO[2] for atom trajectories
79
80
81
82
{
if (!numAtoms)
		return 0;

83
84
85
86
87
if (!solid) {
	eprintf ("SetupAtomsNoTess, error: no solid defined");
	return 0;
}

88
	//http://prideout.net/blog/?p=48 //public domain code
89
	//xyz nxnynz u=atom type ; 7 floats; u only used for colour
90
91
	int e;

92
	int totalatoms=numAtoms[getAtomTimesteps() -1];
93
	
94
	*AtomVAO = new GLuint[4]; //atoms, cloned atoms, unused (bonds use Tess atom positions), trajectories
95
	*AtomIndexBuffer= new GLuint[3];//atoms, cloned atoms, bonds
96
	*AtomVertBuffer = new GLuint[3];//atoms, cloned atoms, trajectories
97

98
	glGenVertexArrays(4, *AtomVAO);
99
	glGenBuffers(2, *AtomIndexBuffer);
100
	glGenBuffers(3, *AtomVertBuffer);
101
102
103
104
105
106
107
	glBindVertexArray((*AtomVAO)[0]);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, (*AtomIndexBuffer)[0]);
	glBindBuffer(GL_ARRAY_BUFFER, (*AtomVertBuffer)[0]);
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);
	glDisableVertexAttribArray(3);
108
	float *tmp = new float[solid->nVerts * 7 * totalatoms];
109
#ifdef INDICESGL32		
110
	int *tmpi = new int[solid->nFaces*3 * totalatoms];
111
112
	int *currenti=tmpi;
#else
113
	unsigned short *tmpi = new unsigned short[solid->nFaces*3 * totalatoms];
114
115
116
117
118
	unsigned short *currenti=tmpi;
#endif

	float *current=tmp;
	//eprintf ("Before For 1");
119
	for (int p=0;p<getAtomTimesteps() ;p++) {
120
121
		for (int a = 0; a < numAtoms[p]-(p==0?0:numAtoms[p-1]); a++) {
			const int atomNumber = static_cast<int>(atoms[p][4 * a + 3]);
122
			const float radius = atomRadius(atomNumber)*atomScaling;
123
			for (int i = 0; i < solid->nVerts; i++) { //verts
124
				for (int k = 0; k < 3; k++) {
125
					*current++ = solid->Verts[3 * i + k]* radius +atoms[p][4 * a + k]; //pos
126
127
				}
				for (int k = 0; k < 3; k++) {
128
					*current++ = solid->Verts[3 * i + k]; //normal
129
				}
130
				*current++ = static_cast<float>(atomNumber);
131
			} //i
132
133
			for (int i = 0; i < solid->nFaces * 3; i++)
				*currenti++ = solid->Faces[i] + (a+(p==0?0:numAtoms[p-1]))*solid->nVerts;
134
135
		} //a
	} //p
136
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) *totalatoms* 7 * solid->nVerts, tmp,
137
138
139
140
141
142
143
144
145
146
			GL_STATIC_DRAW);
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("opengl error %d, glBufferData, l %d\n", e, __LINE__);

		glBufferData(GL_ELEMENT_ARRAY_BUFFER, 
#ifdef INDICESGL32		
	sizeof(int)
#else
	sizeof(unsigned int)
#endif
147
		* totalatoms * 3 * solid->nFaces, tmpi, GL_STATIC_DRAW);
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162


	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (const void *)0);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(3*sizeof(float)));
	glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(6 * sizeof(float)));

	if (glGetError() != GL_NO_ERROR)
		eprintf("opengl error attrib pointer 0\n");

	delete[] tmp;
	delete[] tmpi;
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("opengl error %d, end of SetupAtoms, l %d\n", e, __LINE__);

	//FIXME TODO: cloned atoms
163
	tmp = new float[solid->nVerts * 7 * numClonedAtoms];
164
165
	current=tmp;
#ifdef INDICESGL32		
166
	tmpi = new int[solid->nFaces*3 * numClonedAtoms];
167
168
	currenti=tmpi;
#else
169
	tmpi = new unsigned short[solid->nFaces*3 * numClonedAtoms];
170
171
172
173
174
	currenti=tmpi;
#endif

	for (int a = 0; a < numClonedAtoms; a++) {
		const int atomNumber = static_cast<int>(clonedAtoms[0][4 * a + 3]);
175
		const float radius = atomRadius(atomNumber)*atomScaling;
176
		for (int i = 0; i < solid->nVerts; i++) { //verts
177
				for (int k = 0; k < 3; k++) {
178
					*current++ = solid->Verts[3 * i + k]* radius +clonedAtoms[0][4 * a + k]; //pos
179
180
				}
				for (int k = 0; k < 3; k++) {
181
					*current++ = solid->Verts[3 * i + k]; //normal
182
				}
183
				*current++ =  static_cast<float>(atomNumber);
184
		} //i
185
186
		for (int i = 0; i < solid->nFaces * 3; i++)
			*currenti++ = solid->Faces[i] + a*solid->nVerts;
187
188
189
190
191
192
193
194
195
196
197
	} //a
	
	glBindVertexArray((*AtomVAO)[1]);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, (*AtomIndexBuffer)[1]);
	glBindBuffer(GL_ARRAY_BUFFER, (*AtomVertBuffer)[1]);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);
	glDisableVertexAttribArray(3);

198
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) *numClonedAtoms* 7 * solid->nVerts, tmp,
199
200
201
202
203
204
205
206
207
208
			GL_STATIC_DRAW);
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("opengl error %d, glBufferData, l %d\n", e, __LINE__);
	//eprintf ("After bufferdata, array buffer");
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, 
#ifdef INDICESGL32		
	sizeof(int)
#else
	sizeof(unsigned int)
#endif
209
		* numClonedAtoms * 3 * solid->nFaces, tmpi, GL_STATIC_DRAW);
210
211
212
213
214
215
216
217
218
219
	//eprintf ("After bufferdata, element array buffer");
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7*sizeof(float), (const void *)0);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(3*sizeof(float)));
	glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void *)(6 * sizeof(float)));

	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("opengl error %d, glVertexAttribPointer, l %d\n", e, __LINE__);

	delete[] tmp;
	delete[] tmpi;
220

221
	glBindVertexArray(0);
222
223
224
	return e;
} //SetupAtomsNoTess

225
226
227
228
229
void CleanAtoms (GLuint **AtomVAO /*[4]*/, GLuint **AtomVertBuffer /*[3]*/, GLuint *BondIndices)
{
	if (!numAtoms)
		return;

230
231
232
	if (*AtomVAO==nullptr)
		return;

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
	glDeleteVertexArrays(4, *AtomVAO);
	glDeleteBuffers(3, *AtomVertBuffer);
	glDeleteBuffers(1, BondIndices);

	delete[] (*AtomVAO);
	delete[] (*AtomVertBuffer);
	*AtomVAO=nullptr;
	*AtomVertBuffer=nullptr;


	if (numBonds)
		delete[] numBonds;
	numBonds=nullptr;
	bonds.clear();
}
248

249
GLenum SetupAtoms(GLuint **AtomVAO /*[4]*/, GLuint **AtomVertBuffer /*[3]*/, GLuint *BondIndices)
250
251
{
	if (!numAtoms)
252
		return glGetError();
253
254
255
256
257
258
259
	//rgh FIXME: put this all in the same vao
	
	//http://prideout.net/blog/?p=48 //public domain code
	//xyz u=atom type ; 4 floats
	int e;

	int totalatoms=0;
260
	for (int i=0;i<getAtomTimesteps() ;i++) {
261
262
		totalatoms += numAtoms[i];
	}
263
	//eprintf("SetupAtoms: totalatoms=%d", totalatoms);
264

265
266
	*AtomVAO = new GLuint[4]; //atoms, cloned atoms, bonds, trajectories
	*AtomVertBuffer = new GLuint[3]; //atoms, cloned atoms, trajectories
267

268
269
	glGenVertexArrays(4, *AtomVAO);
	glGenBuffers(3, *AtomVertBuffer);
270
	glGenBuffers(1, BondIndices);
271
272
273
274
275
276
277
278

	glBindVertexArray((*AtomVAO)[0]);
	glBindBuffer(GL_ARRAY_BUFFER, (*AtomVertBuffer)[0]);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);
279
280
281
282

	e=glGetError();
	if (e!=GL_NO_ERROR)
		eprintf ("gl error %d, %s %d", e, __FILE__, __LINE__);
283
284
	float *tmp = new float[4 * totalatoms];
	float *current=tmp;
285
286
287
	
	const int atomlimit=30;

288
	for (int p=0;p<getAtomTimesteps() ;p++) {
289
290
291
292
293
294
		for (int a = 0; a < numAtoms[p]; a++) {
			for (int k = 0; k < 4; k++) {
				*current++ = atoms[p][4 * a + k];
			}
		} //a
	}
295

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
	if (!displaybonds) {
		numBonds=nullptr;
		for (int p=1; p<getAtomTimesteps() ;p++) 
				numAtoms[p]+=numAtoms[p-1];
	} else {
		numBonds=new int[getAtomTimesteps() ];
		//can be slow, add loading screen here if Vive
		for (int p=0;p<getAtomTimesteps() ;p++) {
 
		if (numAtoms[p]<atomlimit) {
			//eprintf ("searching bonds basic");
			//bonds FIXME quadractic complexity	
					for (int a1=0; a1 < numAtoms[p]; a1++) {
						for (int a2=a1+1; a2 < numAtoms[p]; a2++){
							float d=0, r;
							for (int k=0;k<3;k++) {
								float dif=atoms[p][4 * a1 + k]-atoms[p][4 * a2 + k];
								d+=dif*dif;
							}
							r=atomRadius(static_cast<int>(atoms[p][4 * a1 + 3]))+
								atomRadius(static_cast<int>(atoms[p][4 * a2 + 3]));
							if (d*bondscaling<r*r) {// bond
								bonds.push_back(a1+(p==0?0:numAtoms[p-1]));
								bonds.push_back(a2+(p==0?0:numAtoms[p-1]));
							}
321
322
						}
					}
323
324
			} else { //more than 30 atoms, try grid optimization
			//eprintf ("searching bonds grid");
325

326
327
				float m[3];
				float M[3];
328
				for (int k=0; k<3;k++) {
329
					m[k]=M[k]=atoms[p][k];
330
				}
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
				for (int a = 1; a < numAtoms[p]; a++) {
					for (int k=0; k<3;k++) {
						if (m[k]>atoms[p][4*a+k])
							m[k]=atoms[p][4*a+k];
						if (M[k]<atoms[p][4*a+k])
							M[k]=atoms[p][4*a+k];
					}
				}
				grid g(m, M, pow(numAtoms[p], 1.0f/3.0f), bondscaling);
				for (int a = 1; a < numAtoms[p]; a++) 
					g.add(atoms[p]+4*a);
				for (int a = 0; a < numAtoms[p]; a++) {
					std::vector<float*> found=g.find(atoms[p]+4*a);
					for (int b=0;b<found.size();b++) {
						//if (found[b] < tmp+4*a) // already got this bound
						//	continue;
						bonds.push_back(a+(p==0?0:numAtoms[p-1]));
						bonds.push_back(((found[b]-atoms[p])/4)+(p==0?0:numAtoms[p-1]));
					}
350
351
				}
			}
352
353
354
355
356
			numBonds[p]=bonds.size();
			if (p!=0)
				numAtoms[p]+=numAtoms[p-1];
		} //p
	} // showbonds
357
358
359
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (const void *)(0));
	glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (const void *)(3 * sizeof(float)));
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * totalatoms * 4 , tmp,
360
361
362
		GL_STATIC_DRAW);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, glBufferData, l %d\n", e, __LINE__);
363

364
	glBindVertexArray(0);
365
366
367

	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, end of SetupAtoms, l %d\n", e, __LINE__);
368
	
369
370
371
372
373
374
375
376
377
378
379
380
381
382
	if (showTrajectories) {
			//fill the restart buffer
		//use abc for measuring
		float max=0;
		if (has_abc) {
			for (int i=0;i<3;i++)
				for (int j=0;j<3;j++)
				max+=abc[i][j];
			max /=9*2;
		}

		for (unsigned int t=0;t<atomtrajectories.size();t++) {
			atomtrajectoryrestarts.push_back(std::vector<int>());
			atomtrajectoryrestarts[t].push_back(0);
383
			for (int p=1;p<getAtomTimesteps() ;p++) {
384
				int a=atomtrajectories[t];
385
386
387
388
389
				if (has_abc)
					if (fabs(atoms[p][a*4+0]-atoms[p-1][a*4+0])+
						fabs(atoms[p][a*4+1]-atoms[p-1][a*4+1])+
						fabs(atoms[p][a*4+2]-atoms[p-1][a*4+2])>max)
							atomtrajectoryrestarts[t].push_back(p);
390
			}
391
			atomtrajectoryrestarts[t].push_back(getAtomTimesteps() );
392
		}
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
	//need to setup a specific buffer because of GL_MAX_VERTEX_ATTRIB_STRIDE
	//only need xyz, not atom size
	//rgh FIXME: If we use index buffer instead, GPU storage is 1/3 of this
		float *traj = new float[atomtrajectories.size()*TIMESTEPS*3];
		for (unsigned int t = 0; t < atomtrajectories.size(); t++) {
			for (int i=0;i<TIMESTEPS;i++)
				for (int j = 0; j < 3; j++) {
					traj[t*TIMESTEPS * 3 + i * 3 + j] = tmp[i*numAtoms[0]*4+
																+atomtrajectories[t]*4
																+j];
				}
		}
		glBindVertexArray((*AtomVAO)[3]);
		glBindBuffer(GL_ARRAY_BUFFER, (*AtomVertBuffer)[2]);
		glBufferData(GL_ARRAY_BUFFER, sizeof(float) *atomtrajectories.size()*TIMESTEPS * 3, traj,
			GL_STATIC_DRAW);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (const void *)(0));
		glEnableVertexAttribArray(0);
		e = glGetError();
		if ((e = glGetError()) != GL_NO_ERROR)
			eprintf("opengl error %d, creating atom trajectories, l %d\n", e, __LINE__);

		delete[] traj;
416
417
	}
	delete[] tmp;
418
	//bonds
419
420
421
422
423
424
425
426
427
428
429
	if (displaybonds) {
		glBindVertexArray((*AtomVAO)[2]);
		glBindBuffer(GL_ARRAY_BUFFER, (*AtomVertBuffer)[0]);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *BondIndices);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)*bonds.size(), bonds.data(), GL_STATIC_DRAW);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (const void *)(0));
		glEnableVertexAttribArray(0);
		glBindVertexArray(0);
	
		e=glGetError();
		if ((e = glGetError()) != GL_NO_ERROR)
430
			eprintf("opengl error %d, creating chemical bonds, l %d\n", e, __LINE__);
431
	}
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
	//now clones
	if (basisvectorreps ||!clonedAtoms) //do not replicate
		return e;


	glBindVertexArray((*AtomVAO)[1]); //rgh FIXME, only works for TIMESTEPS=1
	glBindBuffer(GL_ARRAY_BUFFER, (*AtomVertBuffer)[1]);
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * clonedAtoms[0].size(), clonedAtoms[0].data(),
			GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (const void *)(0));
	glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (const void *)(3 * sizeof(float)));
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, end of Setup cloned Atoms, l %d\n", e, __LINE__);

	//rgh: we will need these again if we don't have tesselation
	//delete[] clonedAtoms;
	//clonedAtoms=0;
451
	glBindVertexArray(0);
452
453
454
	return e;
}

455
456
457
458
459
460
461
void CleanInfoCube  (GLuint *VAO, GLuint *VertBuffer, GLuint *IndexBuffer)
{
	glDeleteVertexArrays(1, VAO);
	glDeleteBuffers(1, VertBuffer);
	glDeleteBuffers(1, IndexBuffer);
}

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
GLenum SetupInfoCube (GLuint *VAO, GLuint *VertBuffer, GLuint *IndexBuffer)
{
	glGenVertexArrays(1, VAO);
	glGenBuffers(1, VertBuffer);
	glGenBuffers(1, IndexBuffer);

	glBindVertexArray(*VAO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *IndexBuffer);
	glBindBuffer(GL_ARRAY_BUFFER, *VertBuffer);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);
	glDisableVertexAttribArray(3);
	//vec4 pos, vec3 normal, vec2 uv
	const int Nvert=9*26;
	const GLfloat vert[]={
		-1, +1, -1, 0,		0, 0, -1,	0, 1, //-z
		-1, -1, -1,	0,		0, 0, -1,	0, 0,
		+1, +1, -1,	0,		0, 0, -1,	1, 1,
		+1, -1, -1,	0,		0, 0, -1,	1, 0,
		-1, +1, +1, 0,		0, 0, 1,	0, 0,//+z
		-1, -1, +1,	0,		0, 0, 1,	0, 1,
		+1, +1, +1,	0,		0, 0, 1,	1, 0,
		+1, -1, +1,	0,		0, 0, 1,	1, 1,

		+1, -1, -1, 0,		+1, 0, 0,	0, 1,//+x
		+1, -1, +1, 0,		+1, 0, 0,	0, 0,//+x
		+1, +1, -1, 0,		+1, 0, 0,	1, 1,//+x
		+1, +1, +1, 0,		+1, 0, 0,	1, 0,//+x
		-1, -1, -1, 0,		-1, 0, 0,	0, 0,//-x
		-1, -1, +1, 0,		-1, 0, 0,	0, 1,//-x
		-1, +1, -1, 0,		-1, 0, 0,	1, 0,//-x
		-1, +1, +1, 0,		-1, 0, 0,	1, 1,//-x

		-1, 1, +1, 0,		0, -1, 0,	0, 1, //+y
		-1, 1, -1, 0,		0, -1, 0,	0, 0,
		+1, 1, +1, 0,		0, -1, 0,	1, 1,
		+1, 1, -1, 0,		0, -1, 0,	1, 0,
		-1, -1, +1, 0,		0, +1, 0,	0, 0,//-y
		-1, -1, -1, 0,		0, +1, 0,	0, 1,
		+1, -1, +1, 0,		0, +1, 0,	1, 0,
		+1, -1, -1, 0,		0, +1, 0,	1, 1,
		0, 0, 0, 1,			0,0,0,		0,0, //for the line between the cube and the atom
		0, 0, 1, 1,			0, 0, 0,	0, 0, //for the line between the cube and the atom

	};
	const short int ind[]={
		0, 1, 2, //z
		1, 3, 2,
		4, 5, 6,
		5, 7, 6,
		8, 9, 10,//x
		9, 11, 10,
		12, 13, 14,
		13, 15, 14,
		16, 17, 18,//y
		17, 19, 18,
		20, 21, 22,
		21, 23, 22,
	};

	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * Nvert , vert,
			GL_STATIC_DRAW);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(ind), ind, GL_STATIC_DRAW);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (const void *)(0));
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (const void *)(4*sizeof(float)));
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (const void *)(7*sizeof(float)));
	glBindVertexArray(0);

	return glGetError();
}

535
float getMarkerLobeScaling(int l, int k)
536
{
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
	if (l == k)
		return 2.0f;
	return 0.5f;
}

GLenum SetupMarkerNoTess(GLuint *MarkerVAO, GLuint *MarkerVertBuffer, GLuint *MarkerIndexBuffer)
{
	if (!markers)
		return glGetError();

	GLenum e;
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf("opengl error %d, begin of SetupMarkerNoTess\n", e, __LINE__);

	glGenVertexArrays(1, MarkerVAO);
	glGenBuffers(1, MarkerVertBuffer);
	glGenBuffers(1, MarkerIndexBuffer);

	glBindVertexArray(*MarkerVAO);
	glBindBuffer(GL_ARRAY_BUFFER, *MarkerVertBuffer);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *MarkerIndexBuffer);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);
	glDisableVertexAttribArray(3);

	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 10 * sizeof(float), (const void *)0);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 10 * sizeof(float), (const void *)(3 * sizeof(float)));
	glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 10 * sizeof(float), (const void *)(6 * sizeof(float)));

	float *tmp = new float[10 * MARKERSOLID::nVerts*3* TIMESTEPS]; //xyz, nxnynz, rgba; compatible with IsoShaders
	float *current = tmp;
	for (int i = 0; i < TIMESTEPS; i++) {
		for (int l = 0; l < 3; l++) {//3 ellipsoids
			for (int j = 0; j < MARKERSOLID::nVerts; j++) {
				for (int k = 0; k < 3; k++) { //pos
					float s = getMarkerLobeScaling(l, k);
575
					*current++ = s*MARKERSOLID::Verts[j * 3 + k] * markerscaling * atomScaling * atomRadius(0) +
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
						markers[i][k];
				}
				float length=0;
				for (int k = 0; k < 3; k++) { //normal; normalized in IsoShader
					float s = getMarkerLobeScaling(l, k);
					*current = MARKERSOLID::Verts[j * 3 + k]*s;
					length += (*current)*(*current);
					current++;
				}
				length=1.0f / sqrtf(length);
				for (int k=0;k<3;k++) {
					*(current-1-k)*=length;
				}
				for (int k = 0; k < 4; k++) { //colour
					*current++ = markercolours[i][k];
				}
			}
		}
	}
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 10 * MARKERSOLID::nVerts * 3 * TIMESTEPS, tmp,
		GL_STATIC_DRAW);

	delete[] tmp;
#ifdef INDICESGL32		
	int *tmpi=new int[TIMESTEPS * 3 * Icosahedron::nFaces * 3];
	int * currenti;
#else
	short *tmpi = new short[TIMESTEPS * 3 * Icosahedron::nFaces * 3];
	short *currenti;
#endif

	currenti = tmpi;
	for (int i = 0; i < TIMESTEPS; i++) {
		for (int l = 0; l < 3; l++) {//ellipsoids
			for (int j = 0; j < MARKERSOLID::nFaces; j++) {
				for (int k = 0; k < 3; k++) {
					*currenti++ = MARKERSOLID::Faces[j * 3 + k] + 
						MARKERSOLID::nVerts * (l+3*i);
				}
			}
		}
	}

	glBufferData(GL_ELEMENT_ARRAY_BUFFER,
#ifdef INDICESGL32		
		sizeof(int)*MARKERSOLID::nFaces * 3 * TIMESTEPS * 3
#else
		sizeof(unsigned int)*MARKERSOLID::nFaces * 3 * TIMESTEPS * 3
#endif
		, tmpi, GL_STATIC_DRAW);
	delete[] tmpi;
	glBindVertexArray(0);
	return e;
}

631
632
633
634
635
636
void CleanMarker (GLuint *MarkerVAO, GLuint *MarkerVertBuffer)
{
	glDeleteVertexArrays(1, MarkerVAO);
	glDeleteBuffers(1, MarkerVertBuffer);
}

637
638
GLenum SetupMarker(GLuint *MarkerVAO, GLuint *MarkerVertBuffer)
{//requires tesselation
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
	if (!markers)
		return glGetError();
	GLenum e;
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, begin of SetupMarker\n", e, __LINE__);

	glGenVertexArrays(1, MarkerVAO);
	glGenBuffers(1, MarkerVertBuffer);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, glGenBuffers, l %d\n", e, __LINE__);

	glBindVertexArray(*MarkerVAO);
	glBindBuffer(GL_ARRAY_BUFFER, *MarkerVertBuffer);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);

	const float size=atomRadius(0)*atomScaling*markerscaling;
	float *tmp = new float [8*TIMESTEPS];
	for (int i=0;i<TIMESTEPS;i++) {
		for (int j=0;j<3;j++) { //center [3]
			tmp[i*8+j]=markers[i][j];
		}
		tmp[i*8+3]=0.8*size; //size [1]
		for (int j=0;j<4;j++) {//colour[4]
			tmp[i*8+4+j]=markercolours[i][j];
		}
	}
	
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * TIMESTEPS*8 , tmp,
			GL_STATIC_DRAW);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (const void *)(0));
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (const void *)(4*sizeof(float)));
	glBindVertexArray(0);
	return glGetError();
}

678
679
void CleanUnitCell (GLuint *UnitCellVAO, GLuint *UnitCellVertBuffer, GLuint *UnitCellIndexBuffer)
{
680
681
	if (!has_abc)
		return;
682
683
684
685
686
	glDeleteVertexArrays(1, UnitCellVAO);
	glDeleteBuffers(1, UnitCellVertBuffer);
	glDeleteBuffers(1, UnitCellIndexBuffer);
}

687
688
GLenum SetupUnitCell(GLuint *UnitCellVAO, GLuint *UnitCellVertBuffer, GLuint *UnitCellIndexBuffer)
{
689
	//add here both unit cell and supercell
690
	GLenum e;
691
692
693
694
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, begin of SetupUnitCell\n", e, __LINE__);
	if (!has_abc)
		return e;
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
	glGenVertexArrays(1, UnitCellVAO);
	glGenBuffers(1, UnitCellVertBuffer);
	glGenBuffers(1, UnitCellIndexBuffer);
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, glGenBuffers, l %d\n", e, __LINE__);

	glBindVertexArray(*UnitCellVAO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, *UnitCellIndexBuffer);
	glBindBuffer(GL_ARRAY_BUFFER, *UnitCellVertBuffer);

	glEnableVertexAttribArray(0);
	glDisableVertexAttribArray(1);
	glDisableVertexAttribArray(2);
	glDisableVertexAttribArray(3);

710
	float *tmp = new float[3*8*2];
711
	//0, a, b, c, a+b+c, b+c, a+c, a+b
712
	for (int i=0;i<3;i++) { //unit cell
713
714
715
716
717
718
719
720
		tmp[0+i]=0;
		for (int j=0;j<3;j++)
			tmp[3*(j+1)+i]=abc[j][i];
		tmp[3*4+i]=abc[0][i]+abc[1][i]+abc[2][i];
		tmp[3*5+i]=			abc[1][i]+abc[2][i];
		tmp[3*6+i]=abc[0][i]+		abc[2][i];
		tmp[3*7+i]=abc[0][i]+abc[1][i];
	}
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
	float displ[3]={0,0,0};
	if (translations && ISOS) 
		for (int j=0;j<3;j++)
			for (int i=0;i<3;i++)
				displ[i]+=-translations[0][i]*abc[j][i];
	for (int i=0;i<3;i++) { //rgh fixme, add displacement here as well
		tmp[3*8+i]=displ[i];
		for (int j=0;j<3;j++)
			tmp[3*(j+8+1)+i]=abc[j][i]*supercell[j]+displ[i];
		tmp[3*12+i]=abc[0][i]*supercell[0]+abc[1][i]*supercell[1]+abc[2][i]*supercell[2]+displ[i];
		tmp[3*13+i]=			abc[1][i]*supercell[1]+abc[2][i]*supercell[2]+displ[i];
		tmp[3*14+i]=abc[0][i]*supercell[0]+		abc[2][i]*supercell[2]+displ[i];
		tmp[3*15+i]=abc[0][i]*supercell[0]+abc[1][i]*supercell[1]+displ[i];
	}
	int tmpi[12*2*2]={ //lines, unit cell, 
736
737
738
739
740
741
742
743
744
745
746
		0,1, 
		1,6,
		6,3,
		3,0,
		2,7,
		7,4,
		4,5,
		5,2,
		0,2,
		1,7,
		6,4,
747
748
749
750
751
752
753
754
755
756
757
758
759
		3,5, // supercell
		0+8,1+8, 
		1+8,6+8,
		6+8,3+8,
		3+8,0+8,
		2+8,7+8,
		7+8,4+8,
		4+8,5+8,
		5+8,2+8,
		0+8,2+8,
		1+8,7+8,
		6+8,4+8,
		3+8,5+8
760
	};
761
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3*8*2 , tmp,
762
763
			GL_STATIC_DRAW);
	if ((e = glGetError()) != GL_NO_ERROR)
764
		eprintf( "opengl error %d, glBufferData vertex, l %d\n", e, __LINE__);
765
766
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (const void *)(0));
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(tmpi), tmpi, GL_STATIC_DRAW);
767
768
	if ((e = glGetError()) != GL_NO_ERROR)
		eprintf( "opengl error %d, glBufferData index, l %d\n", e, __LINE__);
769
	glBindVertexArray(0);
770
	delete[] tmp;
771
772
773
774
	return e;
}


775
776
bool PrepareUnitCellAtomShader (GLuint *AtomP, GLuint *cellP, GLuint *MarkerP, 
								GLint *AtomMatrixLocation, GLint *UnitCellMatrixLocation,  GLint *UnitCellColourLocation,
777
778
								GLint *MarkerMatrixLocation, GLint *totalatomsLocation, GLint *selectedAtomLocation){
	if (!PrepareAtomShader(AtomP, AtomMatrixLocation, totalatomsLocation, selectedAtomLocation))
779
780
781
782
783
		return false;

	if (!PrepareUnitCellShader(cellP, UnitCellMatrixLocation, UnitCellColourLocation))
		return false;

784
785
786
	if (!PrepareMarkerShader(MarkerP, MarkerMatrixLocation))
		return false;

787
788
789
	return true;
}

790
bool PrepareAtomShader (GLuint *AtomP, GLint *AtomMatrixLocation, GLint *totalatomsLocation, GLint *selectedAtomLocation){
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
		//https://www.gamedev.net/topic/591110-geometry-shader-point-sprites-to-spheres/
	//no rotation, only translations means we can do directional lighting in the shader.
	//FIXME
	//http://stackoverflow.com/questions/40101023/flat-shading-in-webgl
	*AtomP = CompileGLShader(
		AtomShaders[SHADERNAME],
		AtomShaders[SHADERVERTEX],
		AtomShaders[SHADERFRAGMENT],
		AtomShaders[SHADERTESSEVAL]
		);
	*AtomMatrixLocation=glGetUniformLocation(*AtomP, "matrix");
	if( *AtomMatrixLocation == -1 )
	{
		eprintf( "Unable to find matrix uniform in atom shader\n" );
		return false;
	}
807
808
809
810
811
812
	*totalatomsLocation=glGetUniformLocation(*AtomP, "totalatoms");
	if( *totalatomsLocation == -1 )
	{
		eprintf( "Unable to find matrix uniform in atom shader\n" );
		return false;
	}
813
814
815
816
817
818
	*selectedAtomLocation=glGetUniformLocation(*AtomP, "selectedAtom");
	if( *totalatomsLocation == -1 )
	{
		eprintf( "Unable to find selectedAtom uniform in atom shader\n" );
		return false;
	}
819
820
821
	return true;
}

822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
bool PrepareMarkerShader (GLuint *MP, GLint *MMatrixLocation){
		//https://www.gamedev.net/topic/591110-geometry-shader-point-sprites-to-spheres/
	//no rotation, only translations means we can do directional lighting in the shader.
	//FIXME
	//http://stackoverflow.com/questions/40101023/flat-shading-in-webgl
	*MP = CompileGLShader(
		MarkerShaders[SHADERNAME],
		MarkerShaders[SHADERVERTEX],
		MarkerShaders[SHADERFRAGMENT],
		MarkerShaders[SHADERTESSEVAL]
		);
	*MMatrixLocation=glGetUniformLocation(*MP, "matrix");
	if( *MMatrixLocation == -1 )
	{
		eprintf( "Unable to find matrix uniform in atom shader\n" );
		return false;
	}
	return true;
}

842
bool PrepareAtomShaderNoTess (GLuint *AtomP, GLint *AtomMatrixLocation, GLint *totalatomsLocation){
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
		//https://www.gamedev.net/topic/591110-geometry-shader-point-sprites-to-spheres/
	//no rotation, only translations means we can do directional lighting in the shader.
	//FIXME
	//http://stackoverflow.com/questions/40101023/flat-shading-in-webgl
	*AtomP = CompileGLShader(
		AtomShadersNoTess[SHADERNAME],
		AtomShadersNoTess[SHADERVERTEX],
		AtomShadersNoTess[SHADERFRAGMENT],
		AtomShadersNoTess[SHADERTESSEVAL]
		);
	*AtomMatrixLocation=glGetUniformLocation(*AtomP, "matrix");
	if( *AtomMatrixLocation == -1 )
	{
		eprintf( "Unable to find matrix uniform in atom shader no tess\n" );
		return false;
	}
859
860
861
862
863
864
	*totalatomsLocation=glGetUniformLocation(*AtomP, "totalatoms");
	if( *totalatomsLocation == -1 )
	{
		eprintf( "Unable to find matrix uniform in atom shader\n" );
		return false;
	}
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
	return true;
}


bool PrepareUnitCellShader (GLuint *cellP, GLint *UnitCellMatrixLocation,  GLint *UnitCellColourLocation){
	*cellP= CompileGLShader(
		UnitCellShaders[SHADERNAME],
		UnitCellShaders[SHADERVERTEX],
		UnitCellShaders[SHADERFRAGMENT],
		UnitCellShaders[SHADERTESSEVAL]
		);
	*UnitCellMatrixLocation=glGetUniformLocation(*cellP, "matrix");
	if( *UnitCellMatrixLocation == -1 )
	{
		eprintf( "Unable to find matrix uniform in UnitCell shader\n" );
		return false;
	}
	*UnitCellColourLocation=glGetUniformLocation(*cellP, "color");
	if( *UnitCellColourLocation == -1 )
	{
		eprintf( "Unable to find color uniform in UnitCell shader\n" );
		return false;
	}
	return true;
}


/**p: input, f: output*/
void GetDisplacement(int p[3], float f[3])
{
float delta[3][3];
for (int ss=0;ss<3;ss++)
	for (int i=0;i<3;i++)
		delta[ss][i]=static_cast<float>(p[ss])*abc[ss][i];

for (int i=0;i<3;i++)
	f[i]=0;

for (int ss=0;ss<3;ss++)
	for (int i=0;i<3;i++)
		f[i]+=delta[ss][i];
906
}