shaderMutator.cpp 20.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps  *
* version 0.1                                                                  *
* Copyright (C) 2009-2011, IGG Team, LSIIT, University of Strasbourg           *
*                                                                              *
* This library is free software; you can redistribute it and/or modify it      *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your     *
* option) any later version.                                                   *
*                                                                              *
* This library is distributed in the hope that it will be useful, but WITHOUT  *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or        *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License  *
* for more details.                                                            *
*                                                                              *
* You should have received a copy of the GNU Lesser General Public License     *
* along with this library; if not, write to the Free Software Foundation,      *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.           *
*                                                                              *
* Web site: http://cgogn.u-strasbg.fr/                                         *
* Contact information: cgogn@unistra.fr                                        *
*                                                                              *
*******************************************************************************/

#include "Utils/shaderMutator.h"

namespace CGoGN
{

namespace Utils
{

33
34
35
36
37
38
/***********************************************
 *
 * 		Public Section
 *
 ***********************************************/

39
40
41
42
43
44
45
46
47
48
49
ShaderMutator::ShaderMutator(const std:: string& shaderName, const std::string& vertShaderSrc, const std::string& fragShaderSrc, const std::string& geomShaderSrc)
{
	// Store the shader name
	m_shaderName = shaderName;

	// Store the shader source codes
	m_vShaderMutation = vertShaderSrc;
	m_fShaderMutation = fragShaderSrc;
	m_gShaderMutation = geomShaderSrc;
}

50
bool ShaderMutator::containsVariableDeclaration(shaderSrcType srcType, const std::string& variableName)
51
{
52
	bool result = false;
53

54
55
56
57
58
	switch (srcType)
	{
		case VERTEX_SHADER :
			result = srcContainsVariableDeclaration(variableName, m_vShaderMutation);
			break;
59

60
61
62
		case FRAGMENT_SHADER :
			result = srcContainsVariableDeclaration(variableName, m_fShaderMutation);
			break;
63

64
65
66
		case GEOMETRY_SHADER :
			result = srcContainsVariableDeclaration(variableName, m_gShaderMutation);
			break;
67
68
	}

69
	return result;
70
71
}

72
void ShaderMutator::setMinShadingLanguageVersion(shaderSrcType srcType, int version)
73
{
74
	switch (srcType)
75
	{
76
77
78
		case VERTEX_SHADER :
			srcSetMinShadingLanguageVersion(version, m_vShaderMutation);
			break;
79

80
81
82
		case FRAGMENT_SHADER :
			srcSetMinShadingLanguageVersion(version, m_fShaderMutation);
			break;
83

84
85
86
		case GEOMETRY_SHADER :
			srcSetMinShadingLanguageVersion(version, m_gShaderMutation);
			break;
87
88
89
	}
}

90
void ShaderMutator::changeIntConstantValue(shaderSrcType srcType, const std::string& constantName, int newVal)
91
{
92
	switch (srcType)
93
	{
94
		case VERTEX_SHADER :
95
			if (!srcChangeIntConstantValue(newVal, constantName, m_vShaderMutation))
96
97
98
99
100
101
102
103
104
105
106
107
108
109
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeIntConstantValue : "
				<< "Unable to change int constant value in vertex shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

				return;
			}
			break;

		case FRAGMENT_SHADER :
110
			if (!srcChangeIntConstantValue(newVal, constantName, m_fShaderMutation))
111
112
113
114
115
116
117
118
119
120
121
122
123
124
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeIntConstantValue : "
				<< "Unable to change int constant value in fragment shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

				return;
			}
			break;

		case GEOMETRY_SHADER :
125
			if (!srcChangeIntConstantValue(newVal, constantName, m_gShaderMutation))
126
127
128
129
130
131
132
133
134
135
136
137
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::changeIntConstantValue : "
				<< "Unable to change int constant value in geometry shader of "
				<< m_shaderName
				<< ". Constant declaration not found"
				<< CGoGNendl;

				return;
			}
			break;
138
139
140
	}
}

141
void ShaderMutator::insertCodeBeforeMainFunction(shaderSrcType srcType, const std::string& insertedCode)
142
{
143
	switch (srcType)
144
	{
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
		case VERTEX_SHADER :
			if (!srcInsertCodeBeforeMainFunction(insertedCode, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeBeforeMainFunction : "
				<< "Unable to insert source code in vertex shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

				return;
			}
			break;

		case FRAGMENT_SHADER :
			if (!srcInsertCodeBeforeMainFunction(insertedCode, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeBeforeMainFunction : "
				<< "Unable to insert source code in fragment shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

				return;
			}
			break;

		case GEOMETRY_SHADER :
			if (!srcInsertCodeBeforeMainFunction(insertedCode, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeBeforeMainFunction : "
				<< "Unable to insert source code in geometry shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

				return;
			}
			break;
189
190
191
	}
}

192
void ShaderMutator::insertCodeAtMainFunctionBeginning(shaderSrcType srcType, const std::string& insertedCode)
193
{
194
	switch (srcType)
195
	{
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
		case VERTEX_SHADER :
			if (!srcInsertCodeAtMainFunctionBeginning(insertedCode, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionBeginnning : "
				<< "Unable to insert source code in vertex shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

				return;
			}
			break;

		case FRAGMENT_SHADER :
			if (!srcInsertCodeAtMainFunctionBeginning(insertedCode, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionBeginnning : "
				<< "Unable to insert source code in fragment shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

				return;
			}
			break;

		case GEOMETRY_SHADER :
			if (!srcInsertCodeAtMainFunctionBeginning(insertedCode, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionBeginnning : "
				<< "Unable to insert source code in geometry shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration"
				<< CGoGNendl;

				return;
			}
			break;
240
241
242
	}
}

243
void ShaderMutator::insertCodeAtMainFunctionEnd(shaderSrcType srcType, const std::string& insertedCode)
244
{
245
	switch (srcType)
246
	{
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
		case VERTEX_SHADER :
			if (!srcInsertCodeAtMainFunctionEnd(insertedCode, m_vShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionEnd : "
				<< "Unable to insert source code in vertex shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration "
				<< "and as many '{' as '}' in main"
				<< CGoGNendl;

				return;
			}
			break;
262

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
		case FRAGMENT_SHADER :
			if (!srcInsertCodeAtMainFunctionEnd(insertedCode, m_fShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionEnd : "
				<< "Unable to insert source code in fragment shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration "
				<< "and as many '{' as '}' in main"
				<< CGoGNendl;

				return;
			}
			break;
278

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
		case GEOMETRY_SHADER :
			if (!srcInsertCodeAtMainFunctionEnd(insertedCode, m_gShaderMutation))
			{
				CGoGNerr
				<< "ERROR - "
				<< "ShaderMutator::insertCodeAtMainFunctionEnd : "
				<< "Unable to insert source code in geometry shader of "
				<< m_shaderName
				<< ". You should check if the shader has a main function declaration "
				<< "and as many '{' as '}' in main"
				<< CGoGNendl;

				return;
			}
			break;
	}
}
296
297


298
299
300
301
302
/***********************************************
 *
 * 		Private Section
 *
 ***********************************************/
303
304


305
bool ShaderMutator::srcIsCommented(size_t pos, const std::string& src)
306
{
307
308
	// Verify that the given position is not out of the source
	if (pos >= src.length())
309
310
311
	{
		CGoGNerr
		<< "ERROR - "
312
		<< "ShaderMutator::srcIsCommented : "
313
314
315
316
317
		<< "Given position is out of range"
		<< CGoGNendl;
		return false;
	}
	
318
	// Look backward in the source to see if there is any comment symbol (// or /* */)
319
320
	
	// First look for one-line comments
321
	if (srcIsOneLineCommented(pos, src))
322
323
324
325
326
327
		return true;
	
	// Now look for multi-line comments 
	size_t i;
	for (i = pos; i > 0; i--)
	{	
328
		if (src[i] == '/')
329
330
		{
			// End of multi-line comment
331
			if (src[i-1] == '*')
332
333
			{
				// Verify that the end of multi-line comment is not one-line commented !
334
				if (!srcIsOneLineCommented(i, src))
335
336
337
					return false;
			}
		}
338
		else if (src[i] == '*')
339
340
		{
			// Beginning of multi-line comment
341
			if (src[i-1] == '/')
342
343
			{
				// Verify that the beginning of multi-line comment is not one-line commented !
344
				if (!srcIsOneLineCommented(i, src))
345
346
347
348
349
350
351
352
353
354
					return true;
			}
		}
	}
	
	// No one-line or multi-line comments were found
	return false;
	
}

355
bool ShaderMutator::srcIsOneLineCommented(size_t pos, const std::string& src)
356
{
357
358
	// Verify that the given position is not out of the source
	if (pos >= src.length())
359
360
361
	{
		CGoGNerr
		<< "ERROR - "
362
		<< "ShaderMutator::srcIsOneLineCommented : "
363
364
365
366
367
		<< "Given position is out of range"
		<< CGoGNendl;
		return false;
	}
	
368
	// Look backward in the source to see if there is any "//"
369
370
371
372
	size_t i;
	for (i = pos; i > 0; i--)
	{
		// As soon as a '\n' is found, any other "//" will not affect this line anymore
373
		if (src[i] == '\n')
374
			return false;
375
		// Else if a '/' is found, look if it is followed by another
376
377
		else if (src[i] == '/')
			if (src[i-1] == '/')
378
379
380
381
382
383
384
				return true;
	}
	
	// No one-line comments were found
	return false;
}

385
bool ShaderMutator::srcContainsVariableDeclaration(const std::string& variableName, std::string& src)
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
{
	// Regular expression for variable declaration
	// <',' OR white-space[1 or more times]> <variableName> <',' OR ';' OR white-space>
	boost::regex var_re("(,|\\s+)" + variableName + "(,|;|\\s)");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = src.begin();
	std::string::iterator end = src.end();
	while (regex_search(start, end, matches, var_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(src.begin(), matches[0].first);
		
		// Finish if the matched variable is the good one (i.e. not commented)
403
		if (!srcIsCommented(startPosition, src))
404
405
406
407
408
409
410
411
412
413
			return true;
		// Else continue to search for it after last match
		else
			start = matches[0].second;
	}
	
	// At this point no correct match was found
	return false;
}

414
bool ShaderMutator::srcSetMinShadingLanguageVersion(int version, std::string& modifiedSrc)
415
416
{
	// Regular expression for shading language version
417
418
	// <#version> <white-space>[1 or more times] <digit>[1 or more times]
	boost::regex version_re("#version\\s+(\\d+)");
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437

	// Matches results
	boost::match_results <std::string::iterator> matches;

	// Build the version string
	std::string versionStr;
	std::stringstream ss;
	ss << version;
	versionStr = ss.str();

	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, version_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);

		// Change the version number if the matched "#version ..." is the good one (i.e. not commented)
438
		if (!srcIsCommented(startPosition, modifiedSrc))
439
		{
440
			// The submatch Match[1] should be the version number
441
442
443
444
445
			std::string oldVersion(matches[1].first, matches[1].second);
			int oldVersionValue = atoi(oldVersion.c_str());
			size_t oldVersionLength = oldVersion.length();
			size_t oldVersionPosition = std::distance(modifiedSrc.begin(), matches[1].first);

446
			// Replace the old version value only if it is lower than 'version'
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
			if (oldVersionValue < version)
			{
				modifiedSrc.replace(oldVersionPosition, oldVersionLength, versionStr);
				return true;
			}
			else
				return false;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}

	// At this point no correct match was found : insert directly the "#version ..." line
	std::string versionLineStr = "#version " + versionStr + "\n";
	modifiedSrc.insert(0, versionLineStr);

	return true;
}

469
bool ShaderMutator::srcChangeIntConstantValue(int newVal, const std::string& constantName, std::string& modifiedSrc)
470
471
{
	// Regular expression for constant expression
472
473
	// <#define> <white-space>[1 or more times] <constant name> <white-space>[1 or more times] <digit>[1 or more times]
	boost::regex const_re("#define\\s+" + constantName + "\\s+(\\d+)");
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

	// Matches results
	boost::match_results <std::string::iterator> matches;

	// Build the constant value string
	std::string newValStr;
	std::stringstream ss;
	ss << newVal;
	newValStr = ss.str();

	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, const_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);

		// Change the constant value if the matched "#define ..." is the good one (i.e. not commented)
		if (!srcIsCommented(startPosition, modifiedSrc))
		{
			// The submatch Match[1] should be the old constant value
			std::string oldValStr(matches[1].first, matches[1].second);
			size_t oldValLength = oldValStr.length();
			size_t oldValPosition = std::distance(modifiedSrc.begin(), matches[1].first);

500
			// Replace the old constant value
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
			modifiedSrc.replace(oldValPosition, oldValLength, newValStr);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}

	// At this point no correct match was found
	return false;
}

bool ShaderMutator::srcInsertCodeBeforeMainFunction(const std::string& insertedCode, std::string& modifiedSrc)
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
{
	// Regular expression for main function
	// <void> <white-space>[1 or more times] <main> <white-space>[0 or more times] <'('>
	boost::regex main_re("(void)\\s+(main)\\s*\\(");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, main_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);
		
		// Insert and finish if the matched "main" is the good one (i.e. not commented)
533
		if (!srcIsCommented(startPosition, modifiedSrc))
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
		{
			modifiedSrc.insert(startPosition, insertedCode);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}
	
	// At this point no correct match was found
	return false;
}

549
bool ShaderMutator::srcInsertCodeAtMainFunctionBeginning(const std::string& insertedCode, std::string& modifiedSrc)
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
{
	// Regular expression for main function
	// <void> <white-space>[1 or more times] <main> <white-space>[0 or more times]
	// <'('> <white-space>[0 or more times] <')'>
	// <white-space>[0 or more times] <'{'>
	boost::regex main_re("(void)\\s+(main)\\s*\\(\\s*\\)\\s*\\{");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
	while (regex_search(start, end, matches, main_re, boost::format_first_only))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);
		
		// End position of the match
		size_t endPosition = std::distance(modifiedSrc.begin(), matches[0].second);
		
		// Insert and finish if the matched "main" is the good one (i.e. not commented)
572
		if (!srcIsCommented(startPosition, modifiedSrc))
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
		{
			modifiedSrc.insert(endPosition, insertedCode);
			return true;
		}
		// Else continue to search for it after last match
		else
		{
			start = matches[0].second;
		}
	}
	
	// At this point no correct match was found
	return false;
}

588
bool ShaderMutator::srcInsertCodeAtMainFunctionEnd(const std::string& insertedCode, std::string& modifiedSrc)
589
590
591
592
593
594
595
596
597
598
599
600
601
{
	// Regular expression for main function
	// <void> <white-space>[1 or more times] <main> <white-space>[0 or more times]
	// <'('> <white-space>[0 or more times] <')'>
	// <white-space>[0 or more times] <'{'>
	boost::regex main_re("(void)\\s+(main)\\s*\\(\\s*\\)\\s*\\{");
	
	// Matches results
	boost::match_results <std::string::iterator> matches;
	
	// Search for the first expression that matches and isn't commented
	std::string::iterator start = modifiedSrc.begin();
	std::string::iterator end = modifiedSrc.end();
602
	size_t mainFirstBracePos = 0;  // The aim is first to find this position
603
604
605
606
607
608
609
610
611
	while (regex_search(start, end, matches, main_re, boost::format_first_only) && (mainFirstBracePos == 0))
	{
		// Start position of the match
		size_t startPosition = std::distance(modifiedSrc.begin(), matches[0].first);
		
		// End position of the match
		size_t endPosition = std::distance(modifiedSrc.begin(), matches[0].second);
		
		// Get the main first brace position if the matched "main" is the good one (i.e. not commented)
612
		if (!srcIsCommented(startPosition, modifiedSrc))
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
			mainFirstBracePos = endPosition;
		// Else continue to search for it after last match
		else
			start = matches[0].second;
	}
	
	// If mainFirstBracePos is still zero, no correct match was found
	if (mainFirstBracePos == 0)
		return false;
	
	// Else, it is now possible to count the opening and closing braces till the final closing brace of the main function is reached
	int bracesCounter = 1;  // =1 since the first opening brace is counted in, it will be =0 when the final closing brace is reached
	size_t closestBracePos = mainFirstBracePos;
	size_t closestOpeningBracePos;
	size_t closestClosingBracePos;
	while (bracesCounter != 0)
	{
		closestOpeningBracePos = modifiedSrc.find_first_of('{', closestBracePos + 1);
		// If this brace appears to be commented, try to get the next one
632
		while ((closestOpeningBracePos != std::string::npos) && srcIsCommented(closestOpeningBracePos, modifiedSrc))
633
634
635
636
			closestOpeningBracePos = modifiedSrc.find_first_of('{', closestOpeningBracePos + 1);
		
		closestClosingBracePos = modifiedSrc.find_first_of('}', closestBracePos + 1);
		// If this brace appears to be commented, try to get the next one
637
		while ((closestClosingBracePos != std::string::npos) && srcIsCommented(closestClosingBracePos, modifiedSrc))
638
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
			closestClosingBracePos = modifiedSrc.find_first_of('}', closestClosingBracePos + 1);

		// Happens if there is not enough "}" for the corresponding "{"
		if (closestClosingBracePos == std::string::npos)
			return false;

		// Refresh the closest brace position, and increment or decrement the counter
		if (closestClosingBracePos < closestOpeningBracePos)
		{
			closestBracePos = closestClosingBracePos;
			bracesCounter -= 1;
		}
		else
		{
			closestBracePos = closestOpeningBracePos;
			bracesCounter += 1;
		}
	}

	// We should now have the final '}' of the main function
	size_t mainLastBracePos = closestBracePos;
	
	// Insert the source there
	modifiedSrc.insert(mainLastBracePos, insertedCode);
	
	return true;
}

} // namespace Utils

} // namespace CGoGN