File: SCREENFillPoly.c

package info (click to toggle)
psychtoolbox-3 3.0.19.14.dfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 86,796 kB
  • sloc: ansic: 176,245; cpp: 20,103; objc: 5,393; sh: 2,753; python: 1,397; php: 384; makefile: 193; java: 113
file content (293 lines) | stat: -rw-r--r-- 10,733 bytes parent folder | download | duplicates (5)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
189
190
191
192
193
194
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
	SCREENFillPoly.c		
 
	AUTHORS:
 
	Allen.Ingling@nyu.edu			awi 
	mario.kleiner@tuebingen.mpg.de	mk

	PLATFORMS:	
	
	All.
 
	HISTORY:
 
	07/23/04	awi		Created.
	10/12/04	awi		In useString: moved commas to inside [].
	01/12/05     mk     Added a slow-path that draws concave and self-intersecting polygons correctly.
	02/25/05	awi		Added call to PsychUpdateAlphaBlendingFactorLazily().  Drawing now obeys settings by Screen('BlendFunction').
	11/01/08	 mk		Improved speed of slow-path. Still pretty slow -> Most time spent inside gluTesselator(), nothing we could do.
 
	TO DO:
 
	NOTES:
 
	 It would be faster to use one call to glVertex2Dv instead of looping over glVertex2D except that we would have to reshape the matrix. 
	 We have to reshape the matrix because glVertex assumes that values are stored in memory pairwise but MATLAB packs elements columnwise  
	 and FillPolly assumes that a vertex is a row.  We could migrate to the new order except that 2x2 would be ambiguous.  If speed ever 
	 becomes an issue then we could supply a preference to specify vertex columns instead of vertex rows and use glVertex2D.
 */

#include "Screen.h"

#if PSYCH_SYSTEM == PSYCH_LINUX
#define GLUTESSCBCASTER (_GLUfuncptr)
#else
#define GLUTESSCBCASTER
#endif

// Our pointer to the used GLUtesselator object:
static GLUtesselator		*tess = NULL;

// Cache datastructures to reduce or avoid many memory allocation/deallocations:
static GLdouble				*combinerCache = NULL;
static unsigned int			combinerCacheSize = 0;
static unsigned int			combinerCacheSlot = 0;

static double*				tempv = NULL;
static int					tempvsize = 0;

// Callback-Routines for the GLU-Tesselator functions used on the FillPoly - Slow - path:
void APIENTRY PsychtcbBegin(GLenum prim)
{
    PsychGLBegin(NULL, prim);
}

void APIENTRY PsychtcbVertex(void *data)
{
    GLdouble *v = (GLdouble*) data;
    PsychGLVertex4f(NULL, (float) v[0], (float) v[1], (float) v[2], (float) 1);
}

void APIENTRY PsychtcbEnd(void)
{
    PsychGLEnd(NULL);
}

void APIENTRY PsychtcbCombine(GLdouble c[3], void *d[4], GLfloat w[4], void **out)
{
    GLdouble *nv;

    (void) d, (void) w;

    // Free slots available?
    if (combinerCacheSlot >= combinerCacheSize) {
	    // Nope. Need to alloc another cache for up to another 1000 elements:
	    combinerCacheSize = 1000;
	    combinerCacheSlot = 0;
	    combinerCache = (GLdouble *) PsychMallocTemp(sizeof(GLdouble) * 3 * combinerCacheSize);
	    if (NULL == combinerCache) PsychErrorExitMsg(PsychError_outofMemory, "Out of memory condition in Screen('FillPoly')! Not enough space.");
    }

    nv = (GLdouble *) &(combinerCache[combinerCacheSlot * 3]);
    nv[0] = c[0];
    nv[1] = c[1];
    nv[2] = c[2];
    *out = nv;

	combinerCacheSlot++;
}

// Cleanup routine for our tesselators and other data structures. Called from
// ScreenExit.c at Screen shutdown. May be called without OpenGL active! Don't
// use any GL calls here, just plain C-level operations!!
void PsychCleanupSCREENFillPoly(void)
{
	// Release tesselator object and associated data structures, if any:
	if (tess) {
		gluDeleteTess(tess);
		tess=NULL;
	}

	if (tempv) {
		free(tempv);
		tempv = NULL;
		tempvsize = 0;
	}
	
	return;
}

// If you change useString then also change the corresponding synopsis string in ScreenSynopsis.c
static char useString[] = "Screen('FillPoly', windowPtr [,color], pointList [, isConvex]);";
//                                            1           2       3			4
static char synopsisString[] = 
"Fill polygon. \"color\" is the clut index (scalar or [r g b] or [r g b a] vector) that you "
"want to poke into each pixel; default produces white. \"pointList\" is a matrix: each row specifies the (x,y) "
"coordinates of a vertex.\n"
"The optional flag 'isConvex' allows you to tell the routine if the polygon is convex, (value of 1) "
"or if it is concave (value of 0), allowing the routine to skip the test for convexity, thereby "
"saving a bit of computation time in timing sensitive scripts.\n"
"Drawing filled polygons is a rather compute intense and slow operation. In general, drawing "
"convex polygons is pretty fast, drawing concave, but not self-intersecting polygons is much "
"slower (> 30x slower), and drawing concave self-intersecting polygons is extremely slow, "
"e.g. > 2000 times slower. If you have to draw very irregular polygons with may points, "
"it might be a good idea to preprocess them in some way and maybe break them up into "
"a sequence of more convex/regular polygons before submitting them to 'FillPoly'. Or "
"you may want to use some custom written drawing function for your purpose which is "
"optimized for drawing your type of polygons. ";

static char seeAlsoString[] = "FramePoly";	

PsychError SCREENFillPoly(void)  
{	
	PsychColorType				color;
	PsychWindowRecordType		*windowRecord;
	double						whiteValue;
	int							i, mSize, nSize, pSize;
	psych_bool					isArgThere;
	double						*pointList;
	double						isConvex;
	int							j,k;
	int							flag;
	double						z;
	
	combinerCacheSlot = 0;
	combinerCacheSize = 0;
	combinerCache = NULL;
	
	//all sub functions should have these two lines
	PsychPushHelp(useString, synopsisString,seeAlsoString);
	if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};
	
	//check for superfluous arguments
	PsychErrorExit(PsychCapNumInputArgs(4));   //The maximum number of inputs
	PsychErrorExit(PsychCapNumOutputArgs(0));  //The maximum number of outputs
	
	//get the window record from the window record argument and get info from the window record
	PsychAllocInWindowRecordArg(1, kPsychArgRequired, &windowRecord);
	
	//Get the color argument or use the default, then coerce to the form determened by the window depth.  
	isArgThere=PsychCopyInColorArg(2, FALSE, &color);
	if(!isArgThere){
		whiteValue=PsychGetWhiteValueFromWindow(windowRecord);
		PsychLoadColorStruct(&color, kPsychIndexColor, whiteValue ); //index mode will coerce to any other.
	}
 	PsychCoerceColorMode( &color);
	
	//get the list of pairs and validate.  
	PsychAllocInDoubleMatArg(3, kPsychArgRequired, &mSize, &nSize, &pSize, &pointList);
	if(nSize!=2) PsychErrorExitMsg(PsychError_user, "Width of pointList must be 2");
	if(mSize<3)  PsychErrorExitMsg(PsychError_user, "Polygons must consist of at least 3 points; M dimension of pointList was < 3!");
	if(pSize>1)  PsychErrorExitMsg(PsychError_user, "pointList must be a 2D matrix, not a 3D matrix!");
	
	isConvex = -1;
	PsychCopyInDoubleArg(4, kPsychArgOptional, &isConvex);
	
    // On non-OpenGL1/2 we always force isConvex to zero, so the GLU tesselator is
    // always used. This because the tesselator only emits GL_TRIANGLES and GL_TRIANGLE_STRIP
    // and GL_TRIANGLE_FANS primitives which are supported on all current OpenGL API's, whereas
    // or "classic" fast-path needs GL_POLYGONS, which are only supported on classic OpenGL1/2:
    if (!PsychIsGLClassic(windowRecord)) isConvex = 0;

	// Enable this windowRecords framebuffer as current drawingtarget:
	PsychSetDrawingTarget(windowRecord);
	
	// Set default drawshader:
	PsychSetShader(windowRecord, -1);
	
	PsychUpdateAlphaBlendingFactorLazily(windowRecord);		 
	PsychSetGLColor(&color, windowRecord);
	
	///////// Test for convexity ////////
	// This algorithm checks, if the polygon is definitely convex, or not.
	// We take the slow-path, if polygon is non-convex or if we can't prove
	// that it is convex.
	//
	// Algorithm adapted from: http://astronomy.swin.edu.au/~pbourke/geometry/clockwise/
	// Which was written by Paul Bourke, 1998.
	//
	// -> This webpage explains the mathematical principle behind the test and provides
	// a C-Source file which has been adapted for use here.
	//	
	if (isConvex == -1) {
		flag = 0;
		for (i=0; i < mSize; i++) {
			j = (i + 1) % mSize;
			k = (i + 2) % mSize;
			z  = (pointList[j] - pointList[i]) * (pointList[k+mSize] - pointList[j+mSize]);
			z -= (pointList[j+mSize] - pointList[i+mSize]) * (pointList[k] - pointList[j]);
			
			if (z < 0) {
				flag |= 1;
			}
			else if (z > 0) {
				flag |= 2;
			}
			
			if (flag == 3) {
				// This is definitely a CONCAVE polygon --> not Convex --> Take slow but safe path.
				break;
			}
		}
		
		if (flag!=0 && flag!=3) {
			// This is a convex polygon --> Take fast path.
			isConvex = 1;
		}
		else {
			// This is a complex polygon --> can't determine if it is convex or not --> Take slow but safe path.
			isConvex = 0;
		}
	}
			
	////// Switch between fast path and slow path, depending on convexity of polygon:
	if (isConvex > 0) {
		// Convex, non-self-intersecting polygon - Take the fast-path:
		glBegin(GL_POLYGON);
		for(i=0;i<mSize;i++) glVertex2d((GLdouble)pointList[i], (GLdouble)pointList[i+mSize]);
		glEnd();
	}
	else {
		// Possibly concave and/or self-intersecting polygon - At least we couldn't prove it is convex.
		// Take the slow, but safe, path using GLU-Tesselators to break it up into a couple of convex, simple
		// polygons:
		
		// Create and initialize a new GLU-Tesselator object, if needed:
		if (NULL == tess) {
			// Create tesselator:
			tess = gluNewTess();
			if (NULL == tess) PsychErrorExitMsg(PsychError_outofMemory, "Out of memory condition in Screen('FillPoly')! Not enough space.");

			// Assign our callback-functions:
			gluTessCallback(tess, GLU_TESS_BEGIN, GLUTESSCBCASTER PsychtcbBegin);
			gluTessCallback(tess, GLU_TESS_VERTEX, GLUTESSCBCASTER PsychtcbVertex);
			gluTessCallback(tess, GLU_TESS_END, GLUTESSCBCASTER PsychtcbEnd);
			gluTessCallback(tess, GLU_TESS_COMBINE, GLUTESSCBCASTER PsychtcbCombine);

			// Define all tesselated polygons to lie in the x-y plane:
			gluTessNormal(tess, 0, 0, 1);
		}

		// We need to hold the values in a temporary array:
		if (tempvsize < mSize) {
			tempvsize = ((mSize / 1000) + 1) * 1000;
			tempv = (double*) realloc((void*) tempv, sizeof(double) * 3 * tempvsize);
			if (NULL == tempv) PsychErrorExitMsg(PsychError_outofMemory, "Out of memory condition in Screen('FillPoly')! Not enough space.");
		}

		// Now submit our Polygon for tesselation:
		gluTessBeginPolygon(tess, NULL);
		gluTessBeginContour(tess);

		for(i=0; i < mSize; i++) {
			tempv[i*3]=(GLdouble) pointList[i];
			tempv[i*3+1]=(GLdouble) pointList[i+mSize];
			tempv[i*3+2]=0;
			gluTessVertex(tess, (GLdouble*) &(tempv[i*3]), (void*) &(tempv[i*3]));
		}
		
		// Process, finalize and render it by calling our callback-functions:
		gluTessEndContour(tess);
		gluTessEndPolygon (tess);
		
		// Done with drawing the filled polygon. (Slow-Path)
	}
	
	// Mark end of drawing op. This is needed for single buffered drawing:
	PsychFlushGL(windowRecord);
	
	// printf("CombinerCalls %i out of %i allocated.\n", combinerCacheSlot, combinerCacheSize);

	return(PsychError_none);
}