1 /*
2 DSFML - The Simple and Fast Multimedia Library for D
3 
4 Copyright (c) 2013 - 2015 Jeremy DeHaan (dehaan.jeremiah@gmail.com)
5 
6 This software is provided 'as-is', without any express or implied warranty.
7 In no event will the authors be held liable for any damages arising from the use of this software.
8 
9 Permission is granted to anyone to use this software for any purpose, including commercial applications,
10 and to alter it and redistribute it freely, subject to the following restrictions:
11 
12 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
13 If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
14 
15 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
16 
17 3. This notice may not be removed or altered from any source distribution
18 */
19 
20 module dsfml.graphics.shape;
21 
22 import dsfml.system.vector2;
23 
24 import dsfml.graphics.color;
25 import dsfml.graphics.drawable;
26 import dsfml.graphics.primitivetype;
27 import dsfml.graphics.rect;
28 import dsfml.graphics.rendertarget;
29 import dsfml.graphics.renderstates;
30 import dsfml.graphics.texture;
31 import dsfml.graphics.transformable;
32 import dsfml.graphics.vertexarray;
33 
34 import std.typecons : Rebindable;
35 
36 /++
37  + Base class for textured shapes with outline.
38  + 
39  + Shape is a drawable class that allows to define and display a custom convex shape on a render target.
40  + 
41  + It's only an abstract base, it needs to be specialized for concrete types of shapes (circle, rectangle, convex polygon, star, ...).
42  + 
43  + In addition to the attributes provided by the specialized shape classes, a shape always has the following attributes:
44  + - a texture
45  + - a texture rectangle
46  + - a fill color
47  + - an outline color
48  + - an outline thickness
49  + 
50  + Each feature is optional, and can be disabled easily:
51  + - the texture can be null
52  + - the fill/outline colors can be sf::Color::Transparent
53  + - the outline thickness can be zero
54  + 
55  + You can write your own derived shape class, there are only two virtual functions to override:
56  + - getPointCount must return the number of points of the shape
57  + - getPoint must return the points of the shape
58  + 
59  + Authors: Laurent Gomila, Jeremy DeHaan
60  + See_Also: http://www.sfml-dev.org/documentation/2.0/classsf_1_1Shape.php#details
61  +/
62 class Shape : Drawable, Transformable
63 {
64 	mixin NormalTransformable;
65 
66 	protected this()
67 	{
68 		m_vertices = new VertexArray(PrimitiveType.TrianglesFan,0);
69 		m_outlineVertices = new VertexArray(PrimitiveType.TrianglesStrip,0);
70 	}
71 
72 	private
73 	{
74 		Rebindable!(const(Texture)) m_texture; /// Texture of the shape
75 		IntRect m_textureRect; /// Rectangle defining the area of the source texture to display
76 		Color m_fillColor; /// Fill color
77 		Color m_outlineColor; /// Outline color
78 		float m_outlineThickness = 0; /// Thickness of the shape's outline
79 		VertexArray m_vertices; /// Vertex array containing the fill geometry
80 		VertexArray m_outlineVertices; /// Vertex array containing the outline geometry
81 		FloatRect m_insideBounds; /// Bounding rectangle of the inside (fill)
82 		FloatRect m_bounds; /// Bounding rectangle of the whole shape (outline + fill)
83 	}
84 
85 	/**
86 	 * The sub-rectangle of the texture that the shape will display.
87 	 * 
88 	 * The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
89 	 */
90 	@property
91 	{
92 		//Set Texture Rect
93 		IntRect textureRect(IntRect rect)
94 		{
95 			m_textureRect = rect;
96 			updateTexCoords();
97 			return rect;
98 		}
99 		//get texture Rect
100 		IntRect textureRect() const
101 		{
102 			return m_textureRect;
103 		}
104 	}
105 
106 	/**
107 	 * The fill color of the shape.
108 	 * 
109 	 * This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use Color.Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.
110 	 */
111 	@property
112 	{
113 		//set Fill color
114 		Color fillColor(Color color)
115 		{
116 			m_fillColor = color;
117 			updateFillColors();
118 			return color;
119 		}
120 		//get fill color
121 		Color fillColor() const
122 		{
123 			return m_fillColor;
124 		}
125 	}
126 
127 	/**
128 	 * The outline color of the shape.
129 	 * 
130 	 * By default, the shape's outline color is opaque white.
131 	 */
132 	@property
133 	{
134 		//set outline color
135 		Color outlineColor(Color color)
136 		{
137 			m_outlineColor = color;
138 			updateOutlineColors();
139 			return color;
140 		}
141 		//get outline color
142 		Color outlineColor() const
143 		{
144 			return m_outlineColor;
145 		}
146 	}
147 
148 	/**
149 	 * The thickness of the shape's outline.
150 	 * 
151 	 * Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.
152 	 */
153 	@property
154 	{
155 		//set ouline thickness
156 		float outlineThickness(float thickness)
157 		{
158 			m_outlineThickness = thickness;
159 			update();
160 			return thickness;
161 		}
162 		//get outline thickness
163 		float outlineThickness() const
164 		{
165 			return m_outlineThickness;
166 		}
167 	}
168 
169 	/**
170 	 * Get the total number of points in the shape.
171 	 * 
172 	 * Returns: Number of points in the shape.
173 	 */
174 	@property
175 	{
176 		abstract uint pointCount();
177 	}
178 
179 	/**
180 	 * Get the global bounding rectangle of the entity.
181 	 * 
182 	 * The returned rectangle is in global coordinates, which means that it takes in account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the sprite in the global 2D world's coordinate system.
183 	 * 
184 	 * Returns: Global bounding rectangle of the entity
185 	 */
186 	FloatRect getGlobalBounds()
187 	{
188 		return getTransform().transformRect(getLocalBounds());
189 	}
190 
191 	/**
192 	 * Get the local bounding rectangle of the entity.
193 	 * 
194 	 * The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
195 	 * 
196 	 * Returns: Local bounding rectangle of the entity
197 	 */
198 	FloatRect getLocalBounds() const
199 	{
200 		return m_bounds;
201 	}
202 
203 	/**
204 	 * Get a point of the shape.
205 	 * 
206 	 * The result is undefined if index is out of the valid range.
207 	 * 
208 	 * Params:
209 	 * 		index	= Index of the point to get, in range [0 .. getPointCount() - 1]
210 	 * 
211 	 * Returns: Index-th point of the shape
212 	 */
213 	abstract Vector2f getPoint(uint index) const;
214 
215 	/**
216 	 * Get the source texture of the shape.
217 	 * 
218 	 * If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.
219 	 * 
220 	 * Returns: The shape's texture
221 	 */
222 	const(Texture) getTexture() const
223 	{
224 		return m_texture;
225 	}
226 
227 	/**
228 	 * Change the source texture of the shape.
229 	 * 
230 	 * The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behaviour is undefined. texture can be NULL to disable texturing.
231 	 * 
232 	 * If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.
233 	 * 
234 	 * Params:
235 	 * 		texture		= New texture
236 	 * 		resetRect	= Should the texture rect be reset to the size of the new texture?
237 	 */
238 	void setTexture(const(Texture) texture, bool resetRect = false)
239 	{
240 		if((texture !is null) && (resetRect || (m_texture is null)))
241 		{
242 			textureRect = IntRect(0, 0, texture.getSize().x, texture.getSize().y);
243 		}
244 		
245 		m_texture = (texture is null)? null:texture;
246 	}
247 
248 	/**
249 	 * Draw the shape to a render target.
250 	 * 
251 	 * Params:
252 	 * 		renderTarget	= Target to draw to
253 	 * 		renderStates	= Current render states
254 	 */
255 	override void draw(RenderTarget renderTarget, RenderStates renderStates)
256 	{
257 		renderStates.transform = renderStates.transform * getTransform();
258 		renderStates.texture = m_texture;
259 		renderTarget.draw(m_vertices, renderStates);
260 
261 		// Render the outline
262 		if (m_outlineThickness != 0)
263 		{
264 			renderStates.texture = null;
265 			renderTarget.draw(m_outlineVertices, renderStates);
266 		}
267 	}
268 
269 	/**
270 	 * Recompute the internal geometry of the shape.
271 	 * 
272 	 * This function must be called by the derived class everytime the shape's points change (ie. the result of either getPointCount or getPoint is different).
273 	 */
274 	protected void update()
275 	{
276 		// Get the total number of points of the shape
277 		uint count = pointCount();
278 		if (count < 3)
279 		{
280 			m_vertices.resize(0);
281 			m_outlineVertices.resize(0);
282 			return;
283 		}
284 		
285 		m_vertices.resize(count + 2); // + 2 for center and repeated first point
286 		
287 		// Position
288 		for (uint i = 0; i < count; ++i)
289 		{
290 			m_vertices[i + 1].position = getPoint(i);
291 		}
292 		m_vertices[count + 1].position = m_vertices[1].position;
293 		
294 		// Update the bounding rectangle
295 		m_vertices[0] = m_vertices[1]; // so that the result of getBounds() is correct
296 		m_insideBounds = m_vertices.getBounds();
297 
298 		// Compute the center and make it the first vertex
299 		m_vertices[0].position.x = m_insideBounds.left + m_insideBounds.width / 2;
300 		m_vertices[0].position.y = m_insideBounds.top + m_insideBounds.height / 2;
301 		
302 		// Color
303 		updateFillColors();
304 		
305 		// Texture coordinates
306 		updateTexCoords();
307 		
308 		// Outline
309 		updateOutline();
310 	}
311 	
312 	private
313 	{
314 		Vector2f computeNormal(Vector2f p1, Vector2f p2)
315 		{
316 			Vector2f normal = Vector2f(p1.y - p2.y, p2.x - p1.x);
317 			float length = sqrt(normal.x * normal.x + normal.y * normal.y);
318 			if (length != 0f)
319 			{
320 				normal /= length;
321 			}
322 			return normal;
323 		}
324 		
325 		float dotProduct(Vector2f p1, Vector2f p2)
326 		{
327 			return (p1.x * p2.x) + (p1.y * p2.y);
328 		}
329 
330 		//update methods
331 		void updateFillColors()
332 		{
333 			for(uint i = 0; i < m_vertices.getVertexCount(); ++i)
334 			{
335 				m_vertices[i].color = m_fillColor;
336 			}
337 		}
338 		
339 		void updateTexCoords()
340 		{
341 			
342 			for (uint i = 0; i < m_vertices.getVertexCount(); ++i)
343 			{
344 				float xratio = (m_vertices[i].position.x - m_insideBounds.left) / m_insideBounds.width;
345 				float yratio = (m_vertices[i].position.y - m_insideBounds.top) / m_insideBounds.height;
346 				
347 				m_vertices[i].texCoords.x = m_textureRect.left + m_textureRect.width * xratio;
348 				m_vertices[i].texCoords.y = m_textureRect.top + m_textureRect.height * yratio;
349 				
350 			}
351 			
352 			
353 		}
354 		
355 		void updateOutline()
356 		{
357 			uint count = m_vertices.getVertexCount() - 2;
358 			m_outlineVertices.resize((count + 1) * 2);
359 			
360 			for (uint i = 0; i < count; ++i)
361 			{
362 				uint index = i + 1;
363 				
364 				// Get the two segments shared by the current point
365 				Vector2f p0 = (i == 0) ? m_vertices[count].position : m_vertices[index - 1].position;
366 				Vector2f p1 = m_vertices[index].position;
367 				Vector2f p2 = m_vertices[index + 1].position;
368 				
369 				// Compute their normal
370 				Vector2f n1 = computeNormal(p0, p1);
371 				Vector2f n2 = computeNormal(p1, p2);
372 				
373 				// Make sure that the normals point towards the outside of the shape
374 				// (this depends on the order in which the points were defined)
375 				if (dotProduct(n1, m_vertices[0].position - p1) > 0)
376 					n1 = -n1;
377 				if (dotProduct(n2, m_vertices[0].position - p1) > 0)
378 					n2 = -n2;
379 				
380 				// Combine them to get the extrusion direction
381 				float factor = 1f + (n1.x * n2.x + n1.y * n2.y);
382 				Vector2f normal = (n1 + n2) / factor;
383 				
384 				// Update the outline points
385 				m_outlineVertices[i * 2 + 0].position = p1;
386 				m_outlineVertices[i * 2 + 1].position = p1 + normal * m_outlineThickness;
387 			}
388 			
389 			// Duplicate the first point at the end, to close the outline
390 			m_outlineVertices[count * 2 + 0].position = m_outlineVertices[0].position;
391 			m_outlineVertices[count * 2 + 1].position = m_outlineVertices[1].position;
392 			
393 			// Update outline colors
394 			updateOutlineColors();
395 			
396 			// Update the shape's bounds
397 			m_bounds = m_outlineVertices.getBounds();
398 		}
399 		
400 		void updateOutlineColors()
401 		{
402 			for (uint i = 0; i < m_outlineVertices.getVertexCount(); ++i)
403 			{
404 				m_outlineVertices[i].color = m_outlineColor;
405 			}
406 		}
407 
408 	}
409 }
410 
411 unittest
412 {
413 	//meant to be inherited. Unit test?
414 }