2 Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3 For a list of contributors, see the accompanying CONTRIBUTORS file.
5 This file is part of GtkRadiant.
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #if !defined(INCLUDED_BRUSH_H)
23 #define INCLUDED_BRUSH_H
26 /// \brief The brush primitive.
28 /// A collection of planes that define a convex polyhedron.
29 /// The Boundary-Representation of this primitive is a manifold polygonal mesh.
30 /// Each face polygon is represented by a list of vertices in a \c Winding.
31 /// Each vertex is associated with another face that is adjacent to the edge
32 /// formed by itself and the next vertex in the winding. This information can
33 /// be used to find edge-pairs and vertex-rings.
36 #include "debugging/debugging.h"
40 #include "iselection.h"
47 #include "moduleobserver.h"
52 #include "renderable.h"
53 #include "selectable.h"
57 #include "math/frustum.h"
58 #include "selectionlib.h"
60 #include "texturelib.h"
61 #include "container/container.h"
62 #include "generic/bitfield.h"
65 #include "brush_primit.h"
67 #define CONTENTS_DETAIL 0x8000000
82 #define BRUSH_CONNECTIVITY_DEBUG 0
83 #define BRUSH_DEGENERATE_DEBUG 0
85 template<typename TextOuputStreamType>
86 inline TextOuputStreamType& ostream_write(TextOuputStreamType& ostream, const Matrix4& m)
88 return ostream << "(" << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << ", "
89 << m[4] << " " << m[5] << " " << m[6] << " " << m[7] << ", "
90 << m[8] << " " << m[9] << " " << m[10] << " " << m[11] << ", "
91 << m[12] << " " << m[13] << " " << m[14] << " " << m[15] << ")";
94 inline void print_vector3(const Vector3& v)
96 globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n";
99 inline void print_3x3(const Matrix4& m)
101 globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) "
102 << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) "
103 << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n";
108 inline bool texdef_sane(const texdef_t& texdef)
110 return fabs(texdef.shift[0]) < (1 << 16)
111 && fabs(texdef.shift[1]) < (1 << 16);
114 inline void Winding_DrawWireframe(const Winding& winding)
116 glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex);
117 glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints));
120 inline void Winding_Draw(const Winding& winding, const Vector3& normal, RenderStateFlags state)
122 glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex);
124 if((state & RENDER_BUMP) != 0)
126 Vector3 normals[c_brush_maxFaces];
127 typedef Vector3* Vector3Iter;
128 for(Vector3Iter i = normals, end = normals + winding.numpoints; i != end; ++i)
132 if(GlobalShaderCache().useShaderLanguage())
134 glNormalPointer(GL_FLOAT, sizeof(Vector3), normals);
135 glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord);
136 glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent);
137 glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent);
141 glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(Vector3), normals);
142 glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord);
143 glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent);
144 glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent);
149 if (state & RENDER_LIGHTING)
151 Vector3 normals[c_brush_maxFaces];
152 typedef Vector3* Vector3Iter;
153 for(Vector3Iter i = normals, last = normals + winding.numpoints; i != last; ++i)
157 glNormalPointer(GL_FLOAT, sizeof(Vector3), normals);
160 if (state & RENDER_TEXTURE)
162 glTexCoordPointer(2, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->texcoord);
166 if (state & RENDER_FILL)
168 glDrawArrays(GL_TRIANGLE_FAN, 0, GLsizei(winding.numpoints));
172 glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints));
175 glDrawArrays(GL_POLYGON, 0, GLsizei(winding.numpoints));
179 const Winding& winding = winding;
181 if(state & RENDER_FILL)
187 glBegin(GL_LINE_LOOP);
190 if (state & RENDER_LIGHTING)
193 for(int i = 0; i < winding.numpoints; ++i)
195 if (state & RENDER_TEXTURE)
196 glTexCoord2fv(&winding.points[i][3]);
197 glVertex3fv(winding.points[i]);
203 const Colour4b colour_vertex(0, 255, 0, 255);
206 #include "shaderlib.h"
208 typedef DoubleVector3 PlanePoints[3];
210 inline bool planepts_equal(const PlanePoints planepts, const PlanePoints other)
212 return planepts[0] == other[0] && planepts[1] == other[1] && planepts[2] == other[2];
215 inline void planepts_assign(PlanePoints planepts, const PlanePoints other)
217 planepts[0] = other[0];
218 planepts[1] = other[1];
219 planepts[2] = other[2];
222 inline void planepts_quantise(PlanePoints planepts, double snap)
224 vector3_snap(planepts[0], snap);
225 vector3_snap(planepts[1], snap);
226 vector3_snap(planepts[2], snap);
229 inline float vector3_max_component(const Vector3& vec3)
231 return std::max(fabsf(vec3[0]), std::max(fabsf(vec3[1]), fabsf(vec3[2])));
234 inline void edge_snap(Vector3& edge, double snap)
236 float scale = static_cast<float>(ceil(fabs(snap / vector3_max_component(edge))));
239 vector3_scale(edge, scale);
241 vector3_snap(edge, snap);
244 inline void planepts_snap(PlanePoints planepts, double snap)
246 Vector3 edge01(vector3_subtracted(planepts[1], planepts[0]));
247 Vector3 edge12(vector3_subtracted(planepts[2], planepts[1]));
248 Vector3 edge20(vector3_subtracted(planepts[0], planepts[2]));
250 double length_squared_01 = vector3_dot(edge01, edge01);
251 double length_squared_12 = vector3_dot(edge12, edge12);
252 double length_squared_20 = vector3_dot(edge20, edge20);
254 vector3_snap(planepts[0], snap);
256 if(length_squared_01 < length_squared_12)
258 if(length_squared_12 < length_squared_20)
260 edge_snap(edge01, snap);
261 edge_snap(edge12, snap);
262 planepts[1] = vector3_added(planepts[0], edge01);
263 planepts[2] = vector3_added(planepts[1], edge12);
267 edge_snap(edge20, snap);
268 edge_snap(edge01, snap);
269 planepts[1] = vector3_added(planepts[0], edge20);
270 planepts[2] = vector3_added(planepts[1], edge01);
275 if(length_squared_01 < length_squared_20)
277 edge_snap(edge01, snap);
278 edge_snap(edge12, snap);
279 planepts[1] = vector3_added(planepts[0], edge01);
280 planepts[2] = vector3_added(planepts[1], edge12);
284 edge_snap(edge12, snap);
285 edge_snap(edge20, snap);
286 planepts[1] = vector3_added(planepts[0], edge12);
287 planepts[2] = vector3_added(planepts[1], edge20);
292 inline PointVertex pointvertex_for_planept(const DoubleVector3& point, const Colour4b& colour)
296 static_cast<float>(point.x()),
297 static_cast<float>(point.y()),
298 static_cast<float>(point.z())
304 inline PointVertex pointvertex_for_windingpoint(const Vector3& point, const Colour4b& colour)
307 vertex3f_for_vector3(point),
312 inline bool check_plane_is_integer(const PlanePoints& planePoints)
314 return !float_is_integer(planePoints[0][0])
315 || !float_is_integer(planePoints[0][1])
316 || !float_is_integer(planePoints[0][2])
317 || !float_is_integer(planePoints[1][0])
318 || !float_is_integer(planePoints[1][1])
319 || !float_is_integer(planePoints[1][2])
320 || !float_is_integer(planePoints[2][0])
321 || !float_is_integer(planePoints[2][1])
322 || !float_is_integer(planePoints[2][2]);
325 inline void brush_check_shader(const char* name)
327 if(!shader_valid(name))
329 globalErrorStream() << "brush face has invalid texture name: '" << name << "'\n";
333 class FaceShaderObserver
336 virtual void realiseShader() = 0;
337 virtual void unrealiseShader() = 0;
340 class FaceShaderObserverRealise
343 void operator()(FaceShaderObserver& observer) const
345 observer.realiseShader();
349 class FaceShaderObserverUnrealise
352 void operator()(FaceShaderObserver& observer) const
354 observer.unrealiseShader();
358 typedef ReferencePair<FaceShaderObserver> FaceShaderObserverPair;
361 class ContentsFlagsValue
367 ContentsFlagsValue(int surfaceFlags, int contentFlags, int value, bool specified) :
368 m_surfaceFlags(surfaceFlags),
369 m_contentFlags(contentFlags),
371 m_specified(specified)
380 inline unsigned int ContentFlags_assignable(unsigned int contentFlags)
382 return contentFlags & ~CONTENTS_DETAIL;
385 inline ContentsFlagsValue ContentsFlagsValue_maskDetail(const ContentsFlagsValue& other)
387 return ContentsFlagsValue(other.m_surfaceFlags, ContentFlags_assignable(other.m_contentFlags), other.m_value, other.m_specified);
391 class FaceShader : public ModuleObserver
397 CopiedString m_shader;
398 ContentsFlagsValue m_flags;
400 SavedState(const FaceShader& faceShader)
402 m_shader = faceShader.getShader();
403 m_flags = faceShader.m_flags;
406 void exportState(FaceShader& faceShader) const
408 faceShader.setShader(m_shader.c_str());
409 faceShader.setFlags(m_flags);
413 CopiedString m_shader;
415 ContentsFlagsValue m_flags;
416 FaceShaderObserverPair m_observers;
420 FaceShader(const char* shader, const ContentsFlagsValue& flags = ContentsFlagsValue(0, 0, 0, false)) :
433 // copy-construction not supported
434 FaceShader(const FaceShader& other);
436 void instanceAttach()
439 m_state->incrementUsed();
441 void instanceDetach()
443 m_state->decrementUsed();
449 ASSERT_MESSAGE(m_state == 0, "shader cannot be captured");
450 brush_check_shader(m_shader.c_str());
451 m_state = GlobalShaderCache().capture(m_shader.c_str());
452 m_state->attach(*this);
456 ASSERT_MESSAGE(m_state != 0, "shader cannot be released");
457 m_state->detach(*this);
458 GlobalShaderCache().release(m_shader.c_str());
464 ASSERT_MESSAGE(!m_realised, "FaceTexdef::realise: already realised");
466 m_observers.forEach(FaceShaderObserverRealise());
470 ASSERT_MESSAGE(m_realised, "FaceTexdef::unrealise: already unrealised");
471 m_observers.forEach(FaceShaderObserverUnrealise());
475 void attach(FaceShaderObserver& observer)
477 m_observers.attach(observer);
480 observer.realiseShader();
484 void detach(FaceShaderObserver& observer)
488 observer.unrealiseShader();
490 m_observers.detach(observer);
493 const char* getShader() const
495 return m_shader.c_str();
497 void setShader(const char* name)
501 m_state->decrementUsed();
508 m_state->incrementUsed();
511 ContentsFlagsValue getFlags() const
513 ASSERT_MESSAGE(m_realised, "FaceShader::getFlags: flags not valid when unrealised");
514 if(!m_flags.m_specified)
516 return ContentsFlagsValue(
517 m_state->getTexture().surfaceFlags,
518 m_state->getTexture().contentFlags,
519 m_state->getTexture().value,
525 void setFlags(const ContentsFlagsValue& flags)
527 ASSERT_MESSAGE(m_realised, "FaceShader::setFlags: flags not valid when unrealised");
528 m_flags = ContentsFlagsValue_maskDetail(flags);
531 Shader* state() const
536 std::size_t width() const
540 return m_state->getTexture().width;
544 std::size_t height() const
548 return m_state->getTexture().height;
552 unsigned int shaderFlags() const
556 return m_state->getFlags();
563 inline void FaceShader_getFlags(const FaceShader& faceShader, ContentsFlagsValue& flags)
565 flags = faceShader.getFlags();
572 class FaceTexdef : public FaceShaderObserver
575 FaceTexdef(const FaceTexdef& other);
577 FaceTexdef& operator=(const FaceTexdef& other);
582 TextureProjection m_projection;
584 SavedState(const FaceTexdef& faceTexdef)
586 m_projection = faceTexdef.m_projection;
589 void exportState(FaceTexdef& faceTexdef) const
591 Texdef_Assign(faceTexdef.m_projection, m_projection);
595 FaceShader& m_shader;
596 TextureProjection m_projection;
597 bool m_projectionInitialised;
602 const TextureProjection& projection,
603 bool projectionInitialised = true
606 m_projection(projection),
607 m_projectionInitialised(projectionInitialised),
608 m_scaleApplied(false)
610 m_shader.attach(*this);
614 m_shader.detach(*this);
619 ASSERT_MESSAGE(!m_scaleApplied, "texture scale aready added");
620 m_scaleApplied = true;
621 m_projection.m_brushprimit_texdef.addScale(m_shader.width(), m_shader.height());
625 ASSERT_MESSAGE(m_scaleApplied, "texture scale aready removed");
626 m_scaleApplied = false;
627 m_projection.m_brushprimit_texdef.removeScale(m_shader.width(), m_shader.height());
632 if(m_projectionInitialised && !m_scaleApplied)
637 void unrealiseShader()
639 if(m_projectionInitialised && m_scaleApplied)
645 void setTexdef(const TextureProjection& projection)
648 Texdef_Assign(m_projection, projection);
652 void shift(float s, float t)
654 ASSERT_MESSAGE(texdef_sane(m_projection.m_texdef), "FaceTexdef::shift: bad texdef");
656 Texdef_Shift(m_projection, s, t);
660 void scale(float s, float t)
663 Texdef_Scale(m_projection, s, t);
667 void rotate(float angle)
670 Texdef_Rotate(m_projection, angle);
674 void fit(const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat)
676 Texdef_FitTexture(m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat);
679 void emitTextureCoordinates(Winding& winding, const Vector3& normal, const Matrix4& localToWorld)
681 Texdef_EmitTextureCoordinates(m_projection, m_shader.width(), m_shader.height(), winding, normal, localToWorld);
684 void transform(const Plane3& plane, const Matrix4& matrix)
687 Texdef_transformLocked(m_projection, m_shader.width(), m_shader.height(), plane, matrix);
691 TextureProjection normalised() const
693 brushprimit_texdef_t tmp(m_projection.m_brushprimit_texdef);
694 tmp.removeScale(m_shader.width(), m_shader.height());
695 return TextureProjection(m_projection.m_texdef, tmp, m_projection.m_basis_s, m_projection.m_basis_t);
697 void setBasis(const Vector3& normal)
700 Normal_GetTransform(normal, basis);
701 m_projection.m_basis_s = Vector3(basis.xx(), basis.yx(), basis.zx());
702 m_projection.m_basis_t = Vector3(-basis.xy(), -basis.yy(), -basis.zy());
706 inline void FaceTexdef_getTexdef(const FaceTexdef& faceTexdef, TextureProjection& projection)
708 projection = faceTexdef.normalised();
711 inline void planepts_print(const PlanePoints& planePoints, TextOutputStream& ostream)
713 ostream << "( " << planePoints[0][0] << " " << planePoints[0][1] << " " << planePoints[0][2] << " ) "
714 << "( " << planePoints[1][0] << " " << planePoints[1][1] << " " << planePoints[1][2] << " ) "
715 << "( " << planePoints[2][0] << " " << planePoints[2][1] << " " << planePoints[2][2] << " )";
719 inline Plane3 Plane3_applyTranslation(const Plane3& plane, const Vector3& translation)
721 Plane3 tmp(plane3_translated(Plane3(plane.normal(), -plane.dist()), translation));
722 return Plane3(tmp.normal(), -tmp.dist());
725 inline Plane3 Plane3_applyTransform(const Plane3& plane, const Matrix4& matrix)
727 Plane3 tmp(plane3_transformed(Plane3(plane.normal(), -plane.dist()), matrix));
728 return Plane3(tmp.normal(), -tmp.dist());
733 PlanePoints m_planepts;
734 Plane3 m_planeCached;
737 Vector3 m_funcStaticOrigin;
739 static EBrushType m_type;
741 static bool isDoom3Plane()
743 return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4;
749 PlanePoints m_planepts;
752 SavedState(const FacePlane& facePlane)
754 if(facePlane.isDoom3Plane())
756 m_plane = facePlane.m_plane;
760 planepts_assign(m_planepts, facePlane.planePoints());
764 void exportState(FacePlane& facePlane) const
766 if(facePlane.isDoom3Plane())
768 facePlane.m_plane = m_plane;
769 facePlane.updateTranslated();
773 planepts_assign(facePlane.planePoints(), m_planepts);
774 facePlane.MakePlane();
779 FacePlane() : m_funcStaticOrigin(0, 0, 0)
782 FacePlane(const FacePlane& other) : m_funcStaticOrigin(0, 0, 0)
786 planepts_assign(m_planepts, other.m_planepts);
791 m_plane = other.m_plane;
801 if(check_plane_is_integer(m_planepts))
803 globalErrorStream() << "non-integer planepts: ";
804 planepts_print(m_planepts, globalErrorStream());
805 globalErrorStream() << "\n";
808 m_planeCached = plane3_for_points(m_planepts);
816 vector3_swap(m_planepts[0], m_planepts[2]);
821 m_planeCached = plane3_flipped(m_plane);
825 void transform(const Matrix4& matrix, bool mirror)
831 bool off = check_plane_is_integer(planePoints());
834 matrix4_transform_point(matrix, m_planepts[0]);
835 matrix4_transform_point(matrix, m_planepts[1]);
836 matrix4_transform_point(matrix, m_planepts[2]);
844 if(check_plane_is_integer(planePoints()))
848 globalErrorStream() << "caused by transform\n";
856 m_planeCached = Plane3_applyTransform(m_planeCached, matrix);
860 void offset(float offset)
864 Vector3 move(vector3_scaled(m_planeCached.normal(), -offset));
866 vector3_subtract(m_planepts[0], move);
867 vector3_subtract(m_planepts[1], move);
868 vector3_subtract(m_planepts[2], move);
874 m_planeCached.d += offset;
879 void updateTranslated()
881 m_planeCached = Plane3_applyTranslation(m_plane, m_funcStaticOrigin);
885 m_plane = Plane3_applyTranslation(m_planeCached, vector3_negated(m_funcStaticOrigin));
889 PlanePoints& planePoints()
893 const PlanePoints& planePoints() const
897 const Plane3& plane3() const
899 return m_planeCached;
901 void setDoom3Plane(const Plane3& plane)
906 const Plane3& getDoom3Plane() const
911 void copy(const FacePlane& other)
915 planepts_assign(m_planepts, other.m_planepts);
920 m_planeCached = other.m_plane;
924 void copy(const Vector3& p0, const Vector3& p1, const Vector3& p2)
935 m_planeCached = plane3_for_points(p2, p1, p0);
942 const double GRID_MIN = 0.125;
944 inline double quantiseInteger(double f)
946 return float_to_integer(f);
949 inline double quantiseFloating(double f)
951 return float_snapped(f, 1.f / (1 << 16));
954 typedef double (*QuantiseFunc)(double f);
961 virtual bool filter(const Face& face) const = 0;
964 bool face_filtered(Face& face);
966 void Brush_addTextureChangedCallback(const Callback& callback);
967 void Brush_textureChanged();
970 extern bool g_brush_texturelock_enabled;
975 virtual void planeChanged() = 0;
976 virtual void connectivityChanged() = 0;
977 virtual void shaderChanged() = 0;
978 virtual void evaluateTransform() = 0;
982 public OpenGLRenderable,
985 public FaceShaderObserver
987 std::size_t m_refcount;
989 class SavedState : public UndoMemento
992 FacePlane::SavedState m_planeState;
993 FaceTexdef::SavedState m_texdefState;
994 FaceShader::SavedState m_shaderState;
996 SavedState(const Face& face) : m_planeState(face.getPlane()), m_texdefState(face.getTexdef()), m_shaderState(face.getShader())
1000 void exportState(Face& face) const
1002 m_planeState.exportState(face.getPlane());
1003 m_shaderState.exportState(face.getShader());
1004 m_texdefState.exportState(face.getTexdef());
1014 static QuantiseFunc m_quantise;
1015 static EBrushType m_type;
1017 PlanePoints m_move_planepts;
1018 PlanePoints m_move_planeptsTransformed;
1021 FacePlane m_planeTransformed;
1022 FaceShader m_shader;
1023 FaceTexdef m_texdef;
1024 TextureProjection m_texdefTransformed;
1030 FaceObserver* m_observer;
1031 UndoObserver* m_undoable_observer;
1034 // assignment not supported
1035 Face& operator=(const Face& other);
1036 // copy-construction not supported
1037 Face(const Face& other);
1041 Face(FaceObserver* observer) :
1043 m_shader(texdef_name_default()),
1044 m_texdef(m_shader, TextureProjection(), false),
1046 m_observer(observer),
1047 m_undoable_observer(0),
1050 m_shader.attach(*this);
1051 m_plane.copy(Vector3(0, 0, 0), Vector3(64, 0, 0), Vector3(0, 64, 0));
1052 m_texdef.setBasis(m_plane.plane3().normal());
1060 const TextureProjection& projection,
1061 FaceObserver* observer
1065 m_texdef(m_shader, projection),
1066 m_observer(observer),
1067 m_undoable_observer(0),
1070 m_shader.attach(*this);
1071 m_plane.copy(p0, p1, p2);
1072 m_texdef.setBasis(m_plane.plane3().normal());
1076 Face(const Face& other, FaceObserver* observer) :
1078 m_shader(other.m_shader.getShader(), other.m_shader.m_flags),
1079 m_texdef(m_shader, other.getTexdef().normalised()),
1080 m_observer(observer),
1081 m_undoable_observer(0),
1084 m_shader.attach(*this);
1085 m_plane.copy(other.m_plane);
1086 planepts_assign(m_move_planepts, other.m_move_planepts);
1087 m_texdef.setBasis(m_plane.plane3().normal());
1093 m_shader.detach(*this);
1099 m_observer->planeChanged();
1102 void realiseShader()
1104 m_observer->shaderChanged();
1106 void unrealiseShader()
1110 void instanceAttach(MapFile* map)
1112 m_shader.instanceAttach();
1114 m_undoable_observer = GlobalUndoSystem().observer(this);
1115 GlobalFilterSystem().registerFilterable(*this);
1117 void instanceDetach(MapFile* map)
1119 GlobalFilterSystem().unregisterFilterable(*this);
1120 m_undoable_observer = 0;
1121 GlobalUndoSystem().release(this);
1123 m_shader.instanceDetach();
1126 void render(RenderStateFlags state) const
1128 Winding_Draw(m_winding, m_planeTransformed.plane3().normal(), state);
1131 void updateFiltered()
1133 m_filtered = face_filtered(*this);
1135 bool isFiltered() const
1146 if(m_undoable_observer != 0)
1148 m_undoable_observer->save(this);
1153 UndoMemento* exportState() const
1155 return new SavedState(*this);
1157 void importState(const UndoMemento* data)
1161 static_cast<const SavedState*>(data)->exportState(*this);
1164 m_observer->connectivityChanged();
1166 m_observer->shaderChanged();
1176 if(--m_refcount == 0)
1186 bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const
1188 return volume.TestPlane(Plane3(plane3().normal(), -plane3().dist()), localToWorld);
1191 void render(Renderer& renderer, const Matrix4& localToWorld) const
1193 renderer.SetState(m_shader.state(), Renderer::eFullMaterials);
1194 renderer.addRenderable(*this, localToWorld);
1197 void transform(const Matrix4& matrix, bool mirror)
1199 if(g_brush_texturelock_enabled)
1201 Texdef_transformLocked(m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix);
1204 m_planeTransformed.transform(matrix, mirror);
1207 ASSERT_MESSAGE(projectionaxis_for_normal(normal) == projectionaxis_for_normal(plane3().normal()), "bleh");
1209 m_observer->planeChanged();
1212 void assign_planepts(const PlanePoints planepts)
1214 m_planeTransformed.copy(planepts[0], planepts[1], planepts[2]);
1215 m_observer->planeChanged();
1218 /// \brief Reverts the transformable state of the brush to identity.
1219 void revertTransform()
1221 m_planeTransformed = m_plane;
1222 planepts_assign(m_move_planeptsTransformed, m_move_planepts);
1223 m_texdefTransformed = m_texdef.m_projection;
1225 void freezeTransform()
1228 m_plane = m_planeTransformed;
1229 planepts_assign(m_move_planepts, m_move_planeptsTransformed);
1230 m_texdef.m_projection = m_texdefTransformed;
1233 void update_move_planepts_vertex(std::size_t index, PlanePoints planePoints)
1235 std::size_t numpoints = getWinding().numpoints;
1236 ASSERT_MESSAGE(index < numpoints, "update_move_planepts_vertex: invalid index");
1238 std::size_t opposite = Winding_Opposite(getWinding(), index);
1239 std::size_t adjacent = Winding_wrap(getWinding(), opposite+numpoints-1);
1240 planePoints[0] = getWinding()[opposite].vertex;
1241 planePoints[1] = getWinding()[index].vertex;
1242 planePoints[2] = getWinding()[adjacent].vertex;
1243 // winding points are very inaccurate, so they must be quantised before using them to generate the face-plane
1244 planepts_quantise(planePoints, GRID_MIN);
1247 void snapto(float snap)
1252 ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane before snap to grid");
1253 planepts_snap(m_plane.planePoints(), snap);
1254 ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane after snap to grid");
1256 PlanePoints planePoints;
1257 update_move_planepts_vertex(0, planePoints);
1258 vector3_snap(planePoints[0], snap);
1259 vector3_snap(planePoints[1], snap);
1260 vector3_snap(planePoints[2], snap);
1261 assign_planepts(planePoints);
1264 SceneChangeNotify();
1265 if(!plane3_valid(m_plane.plane3()))
1267 globalErrorStream() << "WARNING: invalid plane after snap to grid\n";
1273 void testSelect(SelectionTest& test, SelectionIntersection& best)
1275 test.TestPolygon(VertexPointer(reinterpret_cast<VertexPointer::pointer>(&m_winding.points.data()->vertex), sizeof(WindingVertex)), m_winding.numpoints, best);
1278 void testSelect_centroid(SelectionTest& test, SelectionIntersection& best)
1280 test.TestPoint(m_centroid, best);
1283 void shaderChanged()
1285 EmitTextureCoordinates();
1286 Brush_textureChanged();
1287 m_observer->shaderChanged();
1289 SceneChangeNotify();
1292 const char* GetShader() const
1294 return m_shader.getShader();
1296 void SetShader(const char* name)
1299 m_shader.setShader(name);
1305 m_texdefTransformed = m_texdef.m_projection;
1307 void texdefChanged()
1310 EmitTextureCoordinates();
1311 Brush_textureChanged();
1314 void SetTexdef(const TextureProjection& projection)
1317 m_texdef.setTexdef(projection);
1321 void SetFlags(const ContentsFlagsValue& flags)
1324 m_shader.setFlags(flags);
1325 m_observer->shaderChanged();
1329 void ShiftTexdef(float s, float t)
1332 m_texdef.shift(s, t);
1336 void ScaleTexdef(float s, float t)
1339 m_texdef.scale(s, t);
1343 void RotateTexdef(float angle)
1346 m_texdef.rotate(angle);
1350 void FitTexture(float s_repeat, float t_repeat)
1353 m_texdef.fit(m_plane.plane3().normal(), m_winding, s_repeat, t_repeat);
1357 void EmitTextureCoordinates()
1359 Texdef_EmitTextureCoordinates(m_texdefTransformed, m_shader.width(), m_shader.height(), m_winding, plane3().normal(), g_matrix4_identity);
1363 const Vector3& centroid() const
1368 void construct_centroid()
1370 Winding_Centroid(m_winding, plane3(), m_centroid);
1373 const Winding& getWinding() const
1377 Winding& getWinding()
1382 const Plane3& plane3() const
1384 m_observer->evaluateTransform();
1385 return m_planeTransformed.plane3();
1387 FacePlane& getPlane()
1391 const FacePlane& getPlane() const
1395 FaceTexdef& getTexdef()
1399 const FaceTexdef& getTexdef() const
1403 FaceShader& getShader()
1407 const FaceShader& getShader() const
1412 bool isDetail() const
1414 return (m_shader.m_flags.m_contentFlags & CONTENTS_DETAIL) != 0;
1416 void setDetail(bool detail)
1419 if(detail && !isDetail())
1421 m_shader.m_flags.m_contentFlags |= CONTENTS_DETAIL;
1423 else if(!detail && isDetail())
1425 m_shader.m_flags.m_contentFlags &= ~CONTENTS_DETAIL;
1427 m_observer->shaderChanged();
1430 bool contributes() const
1432 return m_winding.numpoints > 2;
1434 bool is_bounded() const
1436 for(Winding::const_iterator i = m_winding.begin(); i != m_winding.end(); ++i)
1438 if((*i).adjacent == c_brush_maxFaces)
1451 std::size_t m_vertex;
1454 FaceVertexId(std::size_t face, std::size_t vertex)
1455 : m_face(face), m_vertex(vertex)
1459 std::size_t getFace() const
1463 std::size_t getVertex() const
1469 typedef std::size_t faceIndex_t;
1471 struct EdgeRenderIndices
1477 : first(0), second(0)
1480 EdgeRenderIndices(const RenderIndex _first, const RenderIndex _second)
1481 : first(_first), second(_second)
1492 : first(c_brush_maxFaces), second(c_brush_maxFaces)
1495 EdgeFaces(const faceIndex_t _first, const faceIndex_t _second)
1496 : first(_first), second(_second)
1501 class RenderableWireframe : public OpenGLRenderable
1504 void render(RenderStateFlags state) const
1507 glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices->colour);
1508 glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices->vertex);
1509 glDrawElements(GL_LINES, GLsizei(m_size<<1), RenderIndexTypeID, m_faceVertex.data());
1512 for(std::size_t i = 0; i < m_size; ++i)
1514 glVertex3fv(&m_vertices[m_faceVertex[i].first].vertex.x);
1515 glVertex3fv(&m_vertices[m_faceVertex[i].second].vertex.x);
1521 Array<EdgeRenderIndices> m_faceVertex;
1523 const PointVertex* m_vertices;
1527 typedef std::vector<Brush*> brush_vector_t;
1532 virtual bool filter(const Brush& brush) const = 0;
1535 bool brush_filtered(Brush& brush);
1536 void add_brush_filter(BrushFilter& filter, int mask, bool invert = false);
1539 /// \brief Returns true if 'self' takes priority when building brush b-rep.
1540 inline bool plane3_inside(const Plane3& self, const Plane3& other)
1542 if(vector3_equal_epsilon(self.normal(), other.normal(), 0.001))
1544 return self.dist() < other.dist();
1549 typedef SmartPointer<Face> FaceSmartPointer;
1550 typedef std::vector<FaceSmartPointer> Faces;
1552 /// \brief Returns the unique-id of the edge adjacent to \p faceVertex in the edge-pair for the set of \p faces.
1553 inline FaceVertexId next_edge(const Faces& faces, FaceVertexId faceVertex)
1555 std::size_t adjacent_face = faces[faceVertex.getFace()]->getWinding()[faceVertex.getVertex()].adjacent;
1556 std::size_t adjacent_vertex = Winding_FindAdjacent(faces[adjacent_face]->getWinding(), faceVertex.getFace());
1558 ASSERT_MESSAGE(adjacent_vertex != c_brush_maxFaces, "connectivity data invalid");
1559 if(adjacent_vertex == c_brush_maxFaces)
1564 return FaceVertexId(adjacent_face, adjacent_vertex);
1567 /// \brief Returns the unique-id of the vertex adjacent to \p faceVertex in the vertex-ring for the set of \p faces.
1568 inline FaceVertexId next_vertex(const Faces& faces, FaceVertexId faceVertex)
1570 FaceVertexId nextEdge = next_edge(faces, faceVertex);
1571 return FaceVertexId(nextEdge.getFace(), Winding_next(faces[nextEdge.getFace()]->getWinding(), nextEdge.getVertex()));
1574 class SelectableEdge
1576 Vector3 getEdge() const
1578 const Winding& winding = getFace().getWinding();
1579 return vector3_mid(winding[m_faceVertex.getVertex()].vertex, winding[Winding_next(winding, m_faceVertex.getVertex())].vertex);
1584 FaceVertexId m_faceVertex;
1586 SelectableEdge(Faces& faces, FaceVertexId faceVertex)
1587 : m_faces(faces), m_faceVertex(faceVertex)
1590 SelectableEdge& operator=(const SelectableEdge& other)
1592 m_faceVertex = other.m_faceVertex;
1596 Face& getFace() const
1598 return *m_faces[m_faceVertex.getFace()];
1601 void testSelect(SelectionTest& test, SelectionIntersection& best)
1603 test.TestPoint(getEdge(), best);
1607 class SelectableVertex
1609 Vector3 getVertex() const
1611 return getFace().getWinding()[m_faceVertex.getVertex()].vertex;
1616 FaceVertexId m_faceVertex;
1618 SelectableVertex(Faces& faces, FaceVertexId faceVertex)
1619 : m_faces(faces), m_faceVertex(faceVertex)
1622 SelectableVertex& operator=(const SelectableVertex& other)
1624 m_faceVertex = other.m_faceVertex;
1628 Face& getFace() const
1630 return *m_faces[m_faceVertex.getFace()];
1633 void testSelect(SelectionTest& test, SelectionIntersection& best)
1635 test.TestPoint(getVertex(), best);
1642 virtual void reserve(std::size_t size) = 0;
1643 virtual void clear() = 0;
1644 virtual void push_back(Face& face) = 0;
1645 virtual void pop_back() = 0;
1646 virtual void erase(std::size_t index) = 0;
1647 virtual void connectivityChanged() = 0;
1649 virtual void edge_clear() = 0;
1650 virtual void edge_push_back(SelectableEdge& edge) = 0;
1652 virtual void vertex_clear() = 0;
1653 virtual void vertex_push_back(SelectableVertex& vertex) = 0;
1655 virtual void DEBUG_verify() const = 0;
1661 virtual void visit(Face& face) const = 0;
1665 public TransformNode,
1670 public FaceObserver,
1676 scene::Node* m_node;
1677 typedef UniqueSet<BrushObserver*> Observers;
1678 Observers m_observers;
1679 UndoObserver* m_undoable_observer;
1686 // cached data compiled from state
1687 Array<PointVertex> m_faceCentroidPoints;
1688 RenderablePointArray m_render_faces;
1690 Array<PointVertex> m_uniqueVertexPoints;
1691 typedef std::vector<SelectableVertex> SelectableVertices;
1692 SelectableVertices m_select_vertices;
1693 RenderablePointArray m_render_vertices;
1695 Array<PointVertex> m_uniqueEdgePoints;
1696 typedef std::vector<SelectableEdge> SelectableEdges;
1697 SelectableEdges m_select_edges;
1698 RenderablePointArray m_render_edges;
1700 Array<EdgeRenderIndices> m_edge_indices;
1701 Array<EdgeFaces> m_edge_faces;
1706 Callback m_evaluateTransform;
1707 Callback m_boundsChanged;
1709 mutable bool m_planeChanged; // b-rep evaluation required
1710 mutable bool m_transformChanged; // transform evaluation required
1714 STRING_CONSTANT(Name, "Brush");
1716 Callback m_lightsChanged;
1719 static Shader* m_state_point;
1722 static EBrushType m_type;
1723 static double m_maxWorldCoord;
1725 Brush(scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) :
1727 m_undoable_observer(0),
1729 m_render_faces(m_faceCentroidPoints, GL_POINTS),
1730 m_render_vertices(m_uniqueVertexPoints, GL_POINTS),
1731 m_render_edges(m_uniqueEdgePoints, GL_POINTS),
1732 m_planeChanged(false),
1733 m_transformChanged(false),
1734 m_evaluateTransform(evaluateTransform),
1735 m_boundsChanged(boundsChanged)
1739 Brush(const Brush& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) :
1741 m_undoable_observer(0),
1743 m_render_faces(m_faceCentroidPoints, GL_POINTS),
1744 m_render_vertices(m_uniqueVertexPoints, GL_POINTS),
1745 m_render_edges(m_uniqueEdgePoints, GL_POINTS),
1746 m_planeChanged(false),
1747 m_transformChanged(false),
1748 m_evaluateTransform(evaluateTransform),
1749 m_boundsChanged(boundsChanged)
1753 Brush(const Brush& other) :
1754 TransformNode(other),
1758 FaceObserver(other),
1763 m_undoable_observer(0),
1765 m_render_faces(m_faceCentroidPoints, GL_POINTS),
1766 m_render_vertices(m_uniqueVertexPoints, GL_POINTS),
1767 m_render_edges(m_uniqueEdgePoints, GL_POINTS),
1768 m_planeChanged(false),
1769 m_transformChanged(false)
1775 ASSERT_MESSAGE(m_observers.empty(), "Brush::~Brush: observers still attached");
1778 // assignment not supported
1779 Brush& operator=(const Brush& other);
1781 void setDoom3GroupOrigin(const Vector3& origin)
1783 //globalOutputStream() << "func_static origin before: " << m_funcStaticOrigin << " after: " << origin << "\n";
1784 for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1786 (*i)->getPlane().m_funcStaticOrigin = origin;
1787 (*i)->getPlane().updateTranslated();
1788 (*i)->planeChanged();
1793 void attach(BrushObserver& observer)
1795 for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1797 observer.push_back(*(*i));
1800 for(SelectableEdges::iterator i = m_select_edges.begin(); i !=m_select_edges.end(); ++i)
1802 observer.edge_push_back(*i);
1805 for(SelectableVertices::iterator i = m_select_vertices.begin(); i != m_select_vertices.end(); ++i)
1807 observer.vertex_push_back(*i);
1810 m_observers.insert(&observer);
1812 void detach(BrushObserver& observer)
1814 m_observers.erase(&observer);
1817 void forEachFace(const BrushVisitor& visitor) const
1819 for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1821 visitor.visit(*(*i));
1825 void forEachFace_instanceAttach(MapFile* map) const
1827 for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1829 (*i)->instanceAttach(map);
1832 void forEachFace_instanceDetach(MapFile* map) const
1834 for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1836 (*i)->instanceDetach(map);
1840 InstanceCounter m_instanceCounter;
1841 void instanceAttach(const scene::Path& path)
1843 if(++m_instanceCounter.m_count == 1)
1845 m_map = path_find_mapfile(path.begin(), path.end());
1846 m_undoable_observer = GlobalUndoSystem().observer(this);
1847 GlobalFilterSystem().registerFilterable(*this);
1848 forEachFace_instanceAttach(m_map);
1852 ASSERT_MESSAGE(path_find_mapfile(path.begin(), path.end()) == m_map, "node is instanced across more than one file");
1855 void instanceDetach(const scene::Path& path)
1857 if(--m_instanceCounter.m_count == 0)
1859 forEachFace_instanceDetach(m_map);
1860 GlobalFilterSystem().unregisterFilterable(*this);
1862 m_undoable_observer = 0;
1863 GlobalUndoSystem().release(this);
1868 const char* name() const
1872 void attach(const NameCallback& callback)
1875 void detach(const NameCallback& callback)
1880 void updateFiltered()
1884 if(brush_filtered(*this))
1886 m_node->enable(scene::Node::eFiltered);
1890 m_node->disable(scene::Node::eFiltered);
1898 m_planeChanged = true;
1902 void shaderChanged()
1907 void evaluateBRep() const
1911 m_planeChanged = false;
1912 const_cast<Brush*>(this)->buildBRep();
1916 void transformChanged()
1918 m_transformChanged = true;
1921 typedef MemberCaller<Brush, &Brush::transformChanged> TransformChangedCaller;
1923 void evaluateTransform()
1925 if(m_transformChanged)
1927 m_transformChanged = false;
1929 m_evaluateTransform();
1932 const Matrix4& localToParent() const
1934 return g_matrix4_identity;
1940 const AABB& localAABB() const
1943 return m_aabb_local;
1946 VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const
1948 return test.TestAABB(m_aabb_local, localToWorld);
1951 void renderComponents(SelectionSystem::EComponentMode mode, Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
1955 case SelectionSystem::eVertex:
1956 renderer.addRenderable(m_render_vertices, localToWorld);
1958 case SelectionSystem::eEdge:
1959 renderer.addRenderable(m_render_edges, localToWorld);
1961 case SelectionSystem::eFace:
1962 renderer.addRenderable(m_render_faces, localToWorld);
1969 void transform(const Matrix4& matrix)
1971 bool mirror = matrix4_handedness(matrix) == MATRIX4_LEFTHANDED;
1973 for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1975 (*i)->transform(matrix, mirror);
1978 void snapto(float snap)
1980 for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1985 void revertTransform()
1987 for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1989 (*i)->revertTransform();
1992 void freezeTransform()
1994 for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1996 (*i)->freezeTransform();
2000 /// \brief Returns the absolute index of the \p faceVertex.
2001 std::size_t absoluteIndex(FaceVertexId faceVertex)
2003 std::size_t index = 0;
2004 for(std::size_t i = 0; i < faceVertex.getFace(); ++i)
2006 index += m_faces[i]->getWinding().numpoints;
2008 return index + faceVertex.getVertex();
2011 void appendFaces(const Faces& other)
2014 for(Faces::const_iterator i = other.begin(); i != other.end(); ++i)
2020 /// \brief The undo memento for a brush stores only the list of face references - the faces are not copied.
2021 class BrushUndoMemento : public UndoMemento
2024 BrushUndoMemento(const Faces& faces) : m_faces(faces)
2041 if(m_undoable_observer != 0)
2043 m_undoable_observer->save(this);
2047 UndoMemento* exportState() const
2049 return new BrushUndoMemento(m_faces);
2052 void importState(const UndoMemento* state)
2055 appendFaces(static_cast<const BrushUndoMemento*>(state)->m_faces);
2058 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2060 (*i)->DEBUG_verify();
2066 return !m_faces.empty() && m_faces.front()->isDetail();
2069 /// \brief Appends a copy of \p face to the end of the face list.
2070 Face* addFace(const Face& face)
2072 if(m_faces.size() == c_brush_maxFaces)
2077 push_back(FaceSmartPointer(new Face(face, this)));
2078 m_faces.back()->setDetail(isDetail());
2080 return m_faces.back();
2083 /// \brief Appends a new face constructed from the parameters to the end of the face list.
2084 Face* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection)
2086 if(m_faces.size() == c_brush_maxFaces)
2091 push_back(FaceSmartPointer(new Face(p0, p1, p2, shader, projection, this)));
2092 m_faces.back()->setDetail(isDetail());
2094 return m_faces.back();
2097 static void constructStatic(EBrushType type)
2100 Face::m_type = type;
2101 FacePlane::m_type = type;
2103 g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_QUAKE;
2104 if(m_type == eBrushTypeQuake3BP || m_type == eBrushTypeDoom3 || m_type == eBrushTypeQuake4)
2106 g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_BRUSHPRIMITIVES;
2107 g_brush_texturelock_enabled = true;
2109 else if(m_type == eBrushTypeHalfLife)
2111 g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_HALFLIFE;
2112 g_brush_texturelock_enabled = true;
2115 Face::m_quantise = (m_type == eBrushTypeQuake) ? quantiseInteger : quantiseFloating;
2117 m_state_point = GlobalShaderCache().capture("$POINT");
2119 static void destroyStatic()
2121 GlobalShaderCache().release("$POINT");
2124 std::size_t DEBUG_size()
2126 return m_faces.size();
2129 typedef Faces::const_iterator const_iterator;
2131 const_iterator begin() const
2133 return m_faces.begin();
2135 const_iterator end() const
2137 return m_faces.end();
2142 return m_faces.back();
2144 const Face* back() const
2146 return m_faces.back();
2148 void reserve(std::size_t size)
2150 m_faces.reserve(size);
2151 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2153 (*i)->reserve(size);
2156 void push_back(Faces::value_type face)
2158 m_faces.push_back(face);
2159 if(m_instanceCounter.m_count != 0)
2161 m_faces.back()->instanceAttach(m_map);
2163 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2165 (*i)->push_back(*face);
2166 (*i)->DEBUG_verify();
2171 if(m_instanceCounter.m_count != 0)
2173 m_faces.back()->instanceDetach(m_map);
2176 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2179 (*i)->DEBUG_verify();
2182 void erase(std::size_t index)
2184 if(m_instanceCounter.m_count != 0)
2186 m_faces[index]->instanceDetach(m_map);
2188 m_faces.erase(m_faces.begin() + index);
2189 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2192 (*i)->DEBUG_verify();
2195 void connectivityChanged()
2197 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2199 (*i)->connectivityChanged();
2206 if(m_instanceCounter.m_count != 0)
2208 forEachFace_instanceDetach(m_map);
2211 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2214 (*i)->DEBUG_verify();
2217 std::size_t size() const
2219 return m_faces.size();
2223 return m_faces.empty();
2226 /// \brief Returns true if any face of the brush contributes to the final B-Rep.
2227 bool hasContributingFaces() const
2229 for(const_iterator i = begin(); i != end(); ++i)
2231 if((*i)->contributes())
2239 /// \brief Removes faces that do not contribute to the brush. This is useful for cleaning up after CSG operations on the brush.
2240 /// Note: removal of empty faces is not performed during direct brush manipulations, because it would make a manipulation irreversible if it created an empty face.
2241 void removeEmptyFaces()
2247 while(i < m_faces.size())
2249 if(!m_faces[i]->contributes())
2262 /// \brief Constructs \p winding from the intersection of \p plane with the other planes of the brush.
2263 void windingForClipPlane(Winding& winding, const Plane3& plane) const
2265 FixedWinding buffer[2];
2268 // get a poly that covers an effectively infinite area
2269 Winding_createInfinite(buffer[swap], plane, m_maxWorldCoord + 1);
2271 // chop the poly by all of the other faces
2273 for (std::size_t i = 0; i < m_faces.size(); ++i)
2275 const Face& clip = *m_faces[i];
2277 if(plane3_equal(clip.plane3(), plane)
2278 || !plane3_valid(clip.plane3()) || !plane_unique(i)
2279 || plane3_opposing(plane, clip.plane3()))
2284 buffer[!swap].clear();
2286 #if BRUSH_CONNECTIVITY_DEBUG
2287 globalOutputStream() << "clip vs face: " << i << "\n";
2291 // flip the plane, because we want to keep the back side
2292 Plane3 clipPlane(vector3_negated(clip.plane3().normal()), -clip.plane3().dist());
2293 Winding_Clip(buffer[swap], plane, clipPlane, i, buffer[!swap]);
2296 #if BRUSH_CONNECTIVITY_DEBUG
2297 for(FixedWinding::Points::iterator k = buffer[!swap].points.begin(), j = buffer[!swap].points.end() - 1; k != buffer[!swap].points.end(); j = k, ++k)
2299 if(vector3_length_squared(vector3_subtracted((*k).vertex, (*j).vertex)) < 1)
2301 globalOutputStream() << "v: " << std::distance(buffer[!swap].points.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n";
2306 //ASSERT_MESSAGE(buffer[!swap].numpoints != 1, "created single-point winding");
2312 Winding_forFixedWinding(winding, buffer[swap]);
2314 #if BRUSH_CONNECTIVITY_DEBUG
2315 Winding_printConnectivity(winding);
2317 for(Winding::iterator i = winding.begin(), j = winding.end() - 1; i != winding.end(); j = i, ++i)
2319 if(vector3_length_squared(vector3_subtracted((*i).vertex, (*j).vertex)) < 1)
2321 globalOutputStream() << "v: " << std::distance(winding.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n";
2327 void update_wireframe(RenderableWireframe& wire, const bool* faces_visible) const
2329 wire.m_faceVertex.resize(m_edge_indices.size());
2330 wire.m_vertices = m_uniqueVertexPoints.data();
2332 for(std::size_t i = 0; i < m_edge_faces.size(); ++i)
2334 if(faces_visible[m_edge_faces[i].first]
2335 || faces_visible[m_edge_faces[i].second])
2337 wire.m_faceVertex[wire.m_size++] = m_edge_indices[i];
2343 void update_faces_wireframe(Array<PointVertex>& wire, const bool* faces_visible) const
2345 std::size_t count = 0;
2346 for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i)
2348 if(faces_visible[i])
2355 Array<PointVertex>::iterator p = wire.begin();
2356 for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i)
2358 if(faces_visible[i])
2360 *p++ = m_faceCentroidPoints[i];
2365 /// \brief Makes this brush a deep-copy of the \p other.
2366 void copy(const Brush& other)
2368 for(Faces::const_iterator i = other.m_faces.begin(); i != other.m_faces.end(); ++i)
2376 void edge_push_back(FaceVertexId faceVertex)
2378 m_select_edges.push_back(SelectableEdge(m_faces, faceVertex));
2379 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2381 (*i)->edge_push_back(m_select_edges.back());
2386 m_select_edges.clear();
2387 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2392 void vertex_push_back(FaceVertexId faceVertex)
2394 m_select_vertices.push_back(SelectableVertex(m_faces, faceVertex));
2395 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2397 (*i)->vertex_push_back(m_select_vertices.back());
2402 m_select_vertices.clear();
2403 for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2405 (*i)->vertex_clear();
2409 /// \brief Returns true if the face identified by \p index is preceded by another plane that takes priority over it.
2410 bool plane_unique(std::size_t index) const
2413 for(std::size_t i = 0; i < m_faces.size(); ++i)
2415 if(index != i && !plane3_inside(m_faces[index]->plane3(), m_faces[i]->plane3()))
2423 /// \brief Removes edges that are smaller than the tolerance used when generating brush windings.
2424 void removeDegenerateEdges()
2426 for (std::size_t i = 0; i < m_faces.size(); ++i)
2428 Winding& winding = m_faces[i]->getWinding();
2429 for(Winding::iterator j = winding.begin(); j != winding.end();)
2431 std::size_t index = std::distance(winding.begin(), j);
2432 std::size_t next = Winding_next(winding, index);
2433 if(Edge_isDegenerate(winding[index].vertex, winding[next].vertex))
2435 #if BRUSH_DEGENERATE_DEBUG
2436 globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate edge adjacent to " << winding[index].adjacent << "\n";
2438 Winding& other = m_faces[winding[index].adjacent]->getWinding();
2439 std::size_t adjacent = Winding_FindAdjacent(other, i);
2440 if(adjacent != c_brush_maxFaces)
2442 other.erase(other.begin() + adjacent);
2454 /// \brief Invalidates faces that have only two vertices in their winding, while preserving edge-connectivity information.
2455 void removeDegenerateFaces()
2457 // save adjacency info for degenerate faces
2458 for (std::size_t i = 0; i < m_faces.size(); ++i)
2460 Winding& degen = m_faces[i]->getWinding();
2462 if(degen.numpoints == 2)
2464 #if BRUSH_DEGENERATE_DEBUG
2465 globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate winding adjacent to " << degen[0].adjacent << ", " << degen[1].adjacent << "\n";
2467 // this is an "edge" face, where the plane touches the edge of the brush
2469 Winding& winding = m_faces[degen[0].adjacent]->getWinding();
2470 std::size_t index = Winding_FindAdjacent(winding, i);
2471 if(index != c_brush_maxFaces)
2473 #if BRUSH_DEGENERATE_DEBUG
2474 globalOutputStream() << "Brush::buildWindings: face " << degen[0].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[1].adjacent << "\n";
2476 winding[index].adjacent = degen[1].adjacent;
2481 Winding& winding = m_faces[degen[1].adjacent]->getWinding();
2482 std::size_t index = Winding_FindAdjacent(winding, i);
2483 if(index != c_brush_maxFaces)
2485 #if BRUSH_DEGENERATE_DEBUG
2486 globalOutputStream() << "Brush::buildWindings: face " << degen[1].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[0].adjacent << "\n";
2488 winding[index].adjacent = degen[0].adjacent;
2497 /// \brief Removes edges that have the same adjacent-face as their immediate neighbour.
2498 void removeDuplicateEdges()
2500 // verify face connectivity graph
2501 for(std::size_t i = 0; i < m_faces.size(); ++i)
2503 //if(m_faces[i]->contributes())
2505 Winding& winding = m_faces[i]->getWinding();
2506 for(std::size_t j = 0; j != winding.numpoints;)
2508 std::size_t next = Winding_next(winding, j);
2509 if(winding[j].adjacent == winding[next].adjacent)
2511 #if BRUSH_DEGENERATE_DEBUG
2512 globalOutputStream() << "Brush::buildWindings: face " << i << ": removed duplicate edge adjacent to face " << winding[j].adjacent << "\n";
2514 winding.erase(winding.begin() + next);
2525 /// \brief Removes edges that do not have a matching pair in their adjacent-face.
2526 void verifyConnectivityGraph()
2528 // verify face connectivity graph
2529 for(std::size_t i = 0; i < m_faces.size(); ++i)
2531 //if(m_faces[i]->contributes())
2533 Winding& winding = m_faces[i]->getWinding();
2534 for(Winding::iterator j = winding.begin(); j != winding.end();)
2536 #if BRUSH_CONNECTIVITY_DEBUG
2537 globalOutputStream() << "Brush::buildWindings: face " << i << ": adjacent to face " << (*j).adjacent << "\n";
2539 // remove unidirectional graph edges
2540 if((*j).adjacent == c_brush_maxFaces
2541 || Winding_FindAdjacent(m_faces[(*j).adjacent]->getWinding(), i) == c_brush_maxFaces)
2543 #if BRUSH_CONNECTIVITY_DEBUG
2544 globalOutputStream() << "Brush::buildWindings: face " << i << ": removing unidirectional connectivity graph edge adjacent to face " << (*j).adjacent << "\n";
2557 /// \brief Returns true if the brush is a finite volume. A brush without a finite volume extends past the maximum world bounds and is not valid.
2560 for(const_iterator i = begin(); i != end(); ++i)
2562 if(!(*i)->is_bounded())
2570 /// \brief Constructs the polygon windings for each face of the brush. Also updates the brush bounding-box and face texture-coordinates.
2571 bool buildWindings()
2575 m_aabb_local = AABB();
2577 for (std::size_t i = 0; i < m_faces.size(); ++i)
2579 Face& f = *m_faces[i];
2581 if(!plane3_valid(f.plane3()) || !plane_unique(i))
2583 f.getWinding().resize(0);
2587 #if BRUSH_CONNECTIVITY_DEBUG
2588 globalOutputStream() << "face: " << i << "\n";
2590 windingForClipPlane(f.getWinding(), f.plane3());
2592 // update brush bounds
2593 const Winding& winding = f.getWinding();
2594 for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i)
2596 aabb_extend_by_point_safe(m_aabb_local, (*i).vertex);
2599 // update texture coordinates
2600 f.EmitTextureCoordinates();
2605 bool degenerate = !isBounded();
2609 // clean up connectivity information.
2610 // these cleanups must be applied in a specific order.
2611 removeDegenerateEdges();
2612 removeDegenerateFaces();
2613 removeDuplicateEdges();
2614 verifyConnectivityGraph();
2620 /// \brief Constructs the face windings and updates anything that depends on them.
2628 class FaceInstanceSet
2630 typedef SelectionList<FaceInstance> FaceInstances;
2631 FaceInstances m_faceInstances;
2633 void insert(FaceInstance& faceInstance)
2635 m_faceInstances.append(faceInstance);
2637 void erase(FaceInstance& faceInstance)
2639 m_faceInstances.erase(faceInstance);
2642 template<typename Functor>
2643 void foreach(Functor functor)
2645 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
2653 return m_faceInstances.empty();
2655 FaceInstance& last() const
2657 return m_faceInstances.back();
2661 extern FaceInstanceSet g_SelectedFaceInstances;
2663 typedef std::list<std::size_t> VertexSelection;
2665 inline VertexSelection::iterator VertexSelection_find(VertexSelection& self, std::size_t value)
2667 return std::find(self.begin(), self.end(), value);
2670 inline VertexSelection::const_iterator VertexSelection_find(const VertexSelection& self, std::size_t value)
2672 return std::find(self.begin(), self.end(), value);
2675 inline VertexSelection::iterator VertexSelection_insert(VertexSelection& self, std::size_t value)
2677 VertexSelection::iterator i = VertexSelection_find(self, value);
2680 self.push_back(value);
2681 return --self.end();
2685 inline void VertexSelection_erase(VertexSelection& self, std::size_t value)
2687 VertexSelection::iterator i = VertexSelection_find(self, value);
2694 inline bool triangle_reversed(std::size_t x, std::size_t y, std::size_t z)
2696 return !((x < y && y < z) || (z < x && x < y) || (y < z && z < x));
2698 template<typename Element>
2699 inline Vector3 triangle_cross(const BasicVector3<Element>& x, const BasicVector3<Element> y, const BasicVector3<Element>& z)
2701 return vector3_cross(y - x, z - x);
2703 template<typename Element>
2704 inline bool triangles_same_winding(const BasicVector3<Element>& x1, const BasicVector3<Element> y1, const BasicVector3<Element>& z1, const BasicVector3<Element>& x2, const BasicVector3<Element> y2, const BasicVector3<Element>& z2)
2706 return vector3_dot(triangle_cross(x1, y1, z1), triangle_cross(x2, y2, z2)) > 0;
2710 typedef const Plane3* PlanePointer;
2711 typedef PlanePointer* PlanesIterator;
2713 class VectorLightList : public LightList
2715 typedef std::vector<const RendererLight*> Lights;
2718 void addLight(const RendererLight& light)
2720 m_lights.push_back(&light);
2726 void evaluateLights() const
2729 void lightsChanged() const
2732 void forEachLight(const RendererLightCallback& callback) const
2734 for(Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i)
2744 ObservedSelectable m_selectable;
2745 ObservedSelectable m_selectableVertices;
2746 ObservedSelectable m_selectableEdges;
2747 SelectionChangeCallback m_selectionChanged;
2749 VertexSelection m_vertexSelection;
2750 VertexSelection m_edgeSelection;
2753 mutable VectorLightList m_lights;
2755 FaceInstance(Face& face, const SelectionChangeCallback& observer) :
2757 m_selectable(SelectedChangedCaller(*this)),
2758 m_selectableVertices(observer),
2759 m_selectableEdges(observer),
2760 m_selectionChanged(observer)
2763 FaceInstance(const FaceInstance& other) :
2764 m_face(other.m_face),
2765 m_selectable(SelectedChangedCaller(*this)),
2766 m_selectableVertices(other.m_selectableVertices),
2767 m_selectableEdges(other.m_selectableEdges),
2768 m_selectionChanged(other.m_selectionChanged)
2771 FaceInstance& operator=(const FaceInstance& other)
2773 m_face = other.m_face;
2781 const Face& getFace() const
2786 void selectedChanged(const Selectable& selectable)
2788 if(selectable.isSelected())
2790 g_SelectedFaceInstances.insert(*this);
2794 g_SelectedFaceInstances.erase(*this);
2796 m_selectionChanged(selectable);
2798 typedef MemberCaller1<FaceInstance, const Selectable&, &FaceInstance::selectedChanged> SelectedChangedCaller;
2800 bool selectedVertices() const
2802 return !m_vertexSelection.empty();
2804 bool selectedEdges() const
2806 return !m_edgeSelection.empty();
2808 bool isSelected() const
2810 return m_selectable.isSelected();
2813 bool selectedComponents() const
2815 return selectedVertices() || selectedEdges() || isSelected();
2817 bool selectedComponents(SelectionSystem::EComponentMode mode) const
2821 case SelectionSystem::eVertex:
2822 return selectedVertices();
2823 case SelectionSystem::eEdge:
2824 return selectedEdges();
2825 case SelectionSystem::eFace:
2826 return isSelected();
2831 void setSelected(SelectionSystem::EComponentMode mode, bool select)
2835 case SelectionSystem::eFace:
2836 m_selectable.setSelected(select);
2838 case SelectionSystem::eVertex:
2839 ASSERT_MESSAGE(!select, "select-all not supported");
2841 m_vertexSelection.clear();
2842 m_selectableVertices.setSelected(false);
2844 case SelectionSystem::eEdge:
2845 ASSERT_MESSAGE(!select, "select-all not supported");
2847 m_edgeSelection.clear();
2848 m_selectableEdges.setSelected(false);
2855 template<typename Functor>
2856 void SelectedVertices_foreach(Functor functor) const
2858 for(VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i)
2860 std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i);
2861 if(index != c_brush_maxFaces)
2863 functor(getFace().getWinding()[index].vertex);
2867 template<typename Functor>
2868 void SelectedEdges_foreach(Functor functor) const
2870 for(VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i)
2872 std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i);
2873 if(index != c_brush_maxFaces)
2875 const Winding& winding = getFace().getWinding();
2876 std::size_t adjacent = Winding_next(winding, index);
2877 functor(vector3_mid(winding[index].vertex, winding[adjacent].vertex));
2881 template<typename Functor>
2882 void SelectedFaces_foreach(Functor functor) const
2886 functor(centroid());
2890 template<typename Functor>
2891 void SelectedComponents_foreach(Functor functor) const
2893 SelectedVertices_foreach(functor);
2894 SelectedEdges_foreach(functor);
2895 SelectedFaces_foreach(functor);
2898 void iterate_selected(AABB& aabb) const
2900 SelectedComponents_foreach(AABBExtendByPoint(aabb));
2903 class RenderablePointVectorPushBack
2905 RenderablePointVector& m_points;
2907 RenderablePointVectorPushBack(RenderablePointVector& points) : m_points(points)
2910 void operator()(const Vector3& point) const
2912 const Colour4b colour_selected(0, 0, 255, 255);
2913 m_points.push_back(pointvertex_for_windingpoint(point, colour_selected));
2917 void iterate_selected(RenderablePointVector& points) const
2919 SelectedComponents_foreach(RenderablePointVectorPushBack(points));
2922 bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const
2924 return m_face->intersectVolume(volume, localToWorld);
2927 void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
2929 if(!m_face->isFiltered() && m_face->contributes() && intersectVolume(volume, localToWorld))
2931 renderer.PushState();
2932 if(selectedComponents())
2934 renderer.Highlight(Renderer::eFace);
2936 m_face->render(renderer, localToWorld);
2937 renderer.PopState();
2941 void testSelect(SelectionTest& test, SelectionIntersection& best)
2943 if(!m_face->isFiltered())
2945 m_face->testSelect(test, best);
2948 void testSelect(Selector& selector, SelectionTest& test)
2950 SelectionIntersection best;
2951 testSelect(test, best);
2954 Selector_add(selector, m_selectable, best);
2957 void testSelect_centroid(Selector& selector, SelectionTest& test)
2959 if(m_face->contributes() && !m_face->isFiltered())
2961 SelectionIntersection best;
2962 m_face->testSelect_centroid(test, best);
2965 Selector_add(selector, m_selectable, best);
2970 void selectPlane(Selector& selector, const Line& line, PlanesIterator first, PlanesIterator last, const PlaneCallback& selectedPlaneCallback)
2972 for(Winding::const_iterator i = getFace().getWinding().begin(); i != getFace().getWinding().end(); ++i)
2974 Vector3 v(vector3_subtracted(line_closest_point(line, (*i).vertex), (*i).vertex));
2975 double dot = vector3_dot(getFace().plane3().normal(), v);
2982 Selector_add(selector, m_selectable);
2984 selectedPlaneCallback(getFace().plane3());
2986 void selectReversedPlane(Selector& selector, const SelectedPlanes& selectedPlanes)
2988 if(selectedPlanes.contains(plane3_flipped(getFace().plane3())))
2990 Selector_add(selector, m_selectable);
2994 void transformComponents(const Matrix4& matrix)
2998 m_face->transform(matrix, false);
3000 if(selectedVertices())
3002 if(m_vertexSelection.size() == 1)
3004 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3005 m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3007 else if(m_vertexSelection.size() == 2)
3009 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3010 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]);
3011 m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3013 else if(m_vertexSelection.size() >= 3)
3015 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]);
3016 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3017 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]);
3018 m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3023 if(m_edgeSelection.size() == 1)
3025 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]);
3026 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3027 m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3029 else if(m_edgeSelection.size() >= 2)
3031 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]);
3032 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3033 matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]);
3034 m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3039 void snapto(float snap)
3041 m_face->snapto(snap);
3044 void snapComponents(float snap)
3050 if(selectedVertices())
3052 vector3_snap(m_face->m_move_planepts[0], snap);
3053 vector3_snap(m_face->m_move_planepts[1], snap);
3054 vector3_snap(m_face->m_move_planepts[2], snap);
3055 m_face->assign_planepts(m_face->m_move_planepts);
3056 planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts);
3057 m_face->freezeTransform();
3061 vector3_snap(m_face->m_move_planepts[0], snap);
3062 vector3_snap(m_face->m_move_planepts[1], snap);
3063 vector3_snap(m_face->m_move_planepts[2], snap);
3064 m_face->assign_planepts(m_face->m_move_planepts);
3065 planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts);
3066 m_face->freezeTransform();
3069 void update_move_planepts_vertex(std::size_t index)
3071 m_face->update_move_planepts_vertex(index, m_face->m_move_planepts);
3073 void update_move_planepts_vertex2(std::size_t index, std::size_t other)
3075 const std::size_t numpoints = m_face->getWinding().numpoints;
3076 ASSERT_MESSAGE(index < numpoints, "select_vertex: invalid index");
3078 const std::size_t opposite = Winding_Opposite(m_face->getWinding(), index, other);
3080 if(triangle_reversed(index, other, opposite))
3082 std::swap(index, other);
3086 triangles_same_winding(
3087 m_face->getWinding()[opposite].vertex,
3088 m_face->getWinding()[index].vertex,
3089 m_face->getWinding()[other].vertex,
3090 m_face->getWinding()[0].vertex,
3091 m_face->getWinding()[1].vertex,
3092 m_face->getWinding()[2].vertex
3094 "update_move_planepts_vertex2: error"
3097 m_face->m_move_planepts[0] = m_face->getWinding()[opposite].vertex;
3098 m_face->m_move_planepts[1] = m_face->getWinding()[index].vertex;
3099 m_face->m_move_planepts[2] = m_face->getWinding()[other].vertex;
3100 planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate
3102 void update_selection_vertex()
3104 if(m_vertexSelection.size() == 0)
3106 m_selectableVertices.setSelected(false);
3110 m_selectableVertices.setSelected(true);
3112 if(m_vertexSelection.size() == 1)
3114 std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin());
3116 if(index != c_brush_maxFaces)
3118 update_move_planepts_vertex(index);
3121 else if(m_vertexSelection.size() == 2)
3123 std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin());
3124 std::size_t other = Winding_FindAdjacent(getFace().getWinding(), *(++m_vertexSelection.begin()));
3126 if(index != c_brush_maxFaces
3127 && other != c_brush_maxFaces)
3129 update_move_planepts_vertex2(index, other);
3134 void select_vertex(std::size_t index, bool select)
3138 VertexSelection_insert(m_vertexSelection, getFace().getWinding()[index].adjacent);
3142 VertexSelection_erase(m_vertexSelection, getFace().getWinding()[index].adjacent);
3145 SceneChangeNotify();
3146 update_selection_vertex();
3149 bool selected_vertex(std::size_t index) const
3151 return VertexSelection_find(m_vertexSelection, getFace().getWinding()[index].adjacent) != m_vertexSelection.end();
3154 void update_move_planepts_edge(std::size_t index)
3156 std::size_t numpoints = m_face->getWinding().numpoints;
3157 ASSERT_MESSAGE(index < numpoints, "select_edge: invalid index");
3159 std::size_t adjacent = Winding_next(m_face->getWinding(), index);
3160 std::size_t opposite = Winding_Opposite(m_face->getWinding(), index);
3161 m_face->m_move_planepts[0] = m_face->getWinding()[index].vertex;
3162 m_face->m_move_planepts[1] = m_face->getWinding()[adjacent].vertex;
3163 m_face->m_move_planepts[2] = m_face->getWinding()[opposite].vertex;
3164 planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate
3166 void update_selection_edge()
3168 if(m_edgeSelection.size() == 0)
3170 m_selectableEdges.setSelected(false);
3174 m_selectableEdges.setSelected(true);
3176 if(m_edgeSelection.size() == 1)
3178 std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_edgeSelection.begin());
3180 if(index != c_brush_maxFaces)
3182 update_move_planepts_edge(index);
3187 void select_edge(std::size_t index, bool select)
3191 VertexSelection_insert(m_edgeSelection, getFace().getWinding()[index].adjacent);
3195 VertexSelection_erase(m_edgeSelection, getFace().getWinding()[index].adjacent);
3198 SceneChangeNotify();
3199 update_selection_edge();
3202 bool selected_edge(std::size_t index) const
3204 return VertexSelection_find(m_edgeSelection, getFace().getWinding()[index].adjacent) != m_edgeSelection.end();
3207 const Vector3& centroid() const
3209 return m_face->centroid();
3212 void connectivityChanged()
3214 // This occurs when a face is added or removed.
3215 // The current vertex and edge selections no longer valid and must be cleared.
3216 m_vertexSelection.clear();
3217 m_selectableVertices.setSelected(false);
3218 m_edgeSelection.clear();
3219 m_selectableEdges.setSelected(false);
3223 class BrushClipPlane : public OpenGLRenderable
3227 static Shader* m_state;
3229 static void constructStatic()
3231 m_state = GlobalShaderCache().capture("$CLIPPER_OVERLAY");
3233 static void destroyStatic()
3235 GlobalShaderCache().release("$CLIPPER_OVERLAY");
3238 void setPlane(const Brush& brush, const Plane3& plane)
3241 if(plane3_valid(m_plane))
3243 brush.windingForClipPlane(m_winding, m_plane);
3247 m_winding.resize(0);
3251 void render(RenderStateFlags state) const
3253 if((state & RENDER_FILL) != 0)
3255 Winding_Draw(m_winding, m_plane.normal(), state);
3259 Winding_DrawWireframe(m_winding);
3263 void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3265 renderer.SetState(m_state, Renderer::eWireframeOnly);
3266 renderer.SetState(m_state, Renderer::eFullMaterials);
3267 renderer.addRenderable(*this, localToWorld);
3271 inline void Face_addLight(const FaceInstance& face, const Matrix4& localToWorld, const RendererLight& light)
3273 const Plane3& facePlane = face.getFace().plane3();
3274 const Vector3& origin = light.aabb().origin;
3275 Plane3 tmp(plane3_transformed(Plane3(facePlane.normal(), -facePlane.dist()), localToWorld));
3276 if(!plane3_test_point(tmp, origin)
3277 || !plane3_test_point(tmp, vector3_added(origin, light.offset())))
3279 face.m_lights.addLight(light);
3285 typedef std::vector<FaceInstance> FaceInstances;
3287 class EdgeInstance : public Selectable
3289 FaceInstances& m_faceInstances;
3290 SelectableEdge* m_edge;
3292 void select_edge(bool select)
3294 FaceVertexId faceVertex = m_edge->m_faceVertex;
3295 m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select);
3296 faceVertex = next_edge(m_edge->m_faces, faceVertex);
3297 m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select);
3299 bool selected_edge() const
3301 FaceVertexId faceVertex = m_edge->m_faceVertex;
3302 if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex()))
3306 faceVertex = next_edge(m_edge->m_faces, faceVertex);
3307 if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex()))
3316 EdgeInstance(FaceInstances& faceInstances, SelectableEdge& edge)
3317 : m_faceInstances(faceInstances), m_edge(&edge)
3320 EdgeInstance& operator=(const EdgeInstance& other)
3322 m_edge = other.m_edge;
3326 void setSelected(bool select)
3328 select_edge(select);
3330 bool isSelected() const
3332 return selected_edge();
3336 void testSelect(Selector& selector, SelectionTest& test)
3338 SelectionIntersection best;
3339 m_edge->testSelect(test, best);
3342 Selector_add(selector, *this, best);
3347 class VertexInstance : public Selectable
3349 FaceInstances& m_faceInstances;
3350 SelectableVertex* m_vertex;
3352 void select_vertex(bool select)
3354 FaceVertexId faceVertex = m_vertex->m_faceVertex;
3357 m_faceInstances[faceVertex.getFace()].select_vertex(faceVertex.getVertex(), select);
3358 faceVertex = next_vertex(m_vertex->m_faces, faceVertex);
3360 while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace());
3362 bool selected_vertex() const
3364 FaceVertexId faceVertex = m_vertex->m_faceVertex;
3367 if(!m_faceInstances[faceVertex.getFace()].selected_vertex(faceVertex.getVertex()))
3371 faceVertex = next_vertex(m_vertex->m_faces, faceVertex);
3373 while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace());
3378 VertexInstance(FaceInstances& faceInstances, SelectableVertex& vertex)
3379 : m_faceInstances(faceInstances), m_vertex(&vertex)
3382 VertexInstance& operator=(const VertexInstance& other)
3384 m_vertex = other.m_vertex;
3388 void setSelected(bool select)
3390 select_vertex(select);
3392 bool isSelected() const
3394 return selected_vertex();
3397 void testSelect(Selector& selector, SelectionTest& test)
3399 SelectionIntersection best;
3400 m_vertex->testSelect(test, best);
3403 Selector_add(selector, *this, best);
3408 class BrushInstanceVisitor
3411 virtual void visit(FaceInstance& face) const = 0;
3414 class BrushInstance :
3415 public BrushObserver,
3416 public scene::Instance,
3419 public SelectionTestable,
3420 public ComponentSelectionTestable,
3421 public ComponentEditable,
3422 public ComponentSnappable,
3423 public PlaneSelectable,
3424 public LightCullable
3428 InstanceTypeCastTable m_casts;
3432 InstanceStaticCast<BrushInstance, Selectable>::install(m_casts);
3433 InstanceContainedCast<BrushInstance, Bounded>::install(m_casts);
3434 InstanceContainedCast<BrushInstance, Cullable>::install(m_casts);
3435 InstanceStaticCast<BrushInstance, Renderable>::install(m_casts);
3436 InstanceStaticCast<BrushInstance, SelectionTestable>::install(m_casts);
3437 InstanceStaticCast<BrushInstance, ComponentSelectionTestable>::install(m_casts);
3438 InstanceStaticCast<BrushInstance, ComponentEditable>::install(m_casts);
3439 InstanceStaticCast<BrushInstance, ComponentSnappable>::install(m_casts);
3440 InstanceStaticCast<BrushInstance, PlaneSelectable>::install(m_casts);
3441 InstanceIdentityCast<BrushInstance>::install(m_casts);
3442 InstanceContainedCast<BrushInstance, Transformable>::install(m_casts);
3444 InstanceTypeCastTable& get()
3453 FaceInstances m_faceInstances;
3455 typedef std::vector<EdgeInstance> EdgeInstances;
3456 EdgeInstances m_edgeInstances;
3457 typedef std::vector<VertexInstance> VertexInstances;
3458 VertexInstances m_vertexInstances;
3460 ObservedSelectable m_selectable;
3462 mutable RenderableWireframe m_render_wireframe;
3463 mutable RenderablePointVector m_render_selected;
3464 mutable AABB m_aabb_component;
3465 mutable Array<PointVertex> m_faceCentroidPointsCulled;
3466 RenderablePointArray m_render_faces_wireframe;
3467 mutable bool m_viewChanged; // requires re-evaluation of view-dependent cached data
3469 BrushClipPlane m_clipPlane;
3471 static Shader* m_state_selpoint;
3473 const LightList* m_lightList;
3475 TransformModifier m_transform;
3477 BrushInstance(const BrushInstance& other); // NOT COPYABLE
3478 BrushInstance& operator=(const BrushInstance& other); // NOT ASSIGNABLE
3480 static Counter* m_counter;
3482 typedef LazyStatic<TypeCasts> StaticTypeCasts;
3484 void lightsChanged()
3486 m_lightList->lightsChanged();
3488 typedef MemberCaller<BrushInstance, &BrushInstance::lightsChanged> LightsChangedCaller;
3490 STRING_CONSTANT(Name, "BrushInstance");
3492 BrushInstance(const scene::Path& path, scene::Instance* parent, Brush& brush) :
3493 Instance(path, parent, this, StaticTypeCasts::instance().get()),
3495 m_selectable(SelectedChangedCaller(*this)),
3496 m_render_selected(GL_POINTS),
3497 m_render_faces_wireframe(m_faceCentroidPointsCulled, GL_POINTS),
3498 m_viewChanged(false),
3499 m_transform(Brush::TransformChangedCaller(m_brush), ApplyTransformCaller(*this))
3501 m_brush.instanceAttach(Instance::path());
3502 m_brush.attach(*this);
3503 m_counter->increment();
3505 m_lightList = &GlobalShaderCache().attach(*this);
3506 m_brush.m_lightsChanged = LightsChangedCaller(*this); ///\todo Make this work with instancing.
3508 Instance::setTransformChangedCallback(LightsChangedCaller(*this));
3512 Instance::setTransformChangedCallback(Callback());
3514 m_brush.m_lightsChanged = Callback();
3515 GlobalShaderCache().detach(*this);
3517 m_counter->decrement();
3518 m_brush.detach(*this);
3519 m_brush.instanceDetach(Instance::path());
3526 const Brush& getBrush() const
3531 Bounded& get(NullType<Bounded>)
3535 Cullable& get(NullType<Cullable>)
3539 Transformable& get(NullType<Transformable>)
3544 void selectedChanged(const Selectable& selectable)
3546 GlobalSelectionSystem().getObserver(SelectionSystem::ePrimitive)(selectable);
3547 GlobalSelectionSystem().onSelectedChanged(*this, selectable);
3549 Instance::selectedChanged();
3551 typedef MemberCaller1<BrushInstance, const Selectable&, &BrushInstance::selectedChanged> SelectedChangedCaller;
3553 void selectedChangedComponent(const Selectable& selectable)
3555 GlobalSelectionSystem().getObserver(SelectionSystem::eComponent)(selectable);
3556 GlobalSelectionSystem().onComponentSelection(*this, selectable);
3558 typedef MemberCaller1<BrushInstance, const Selectable&, &BrushInstance::selectedChangedComponent> SelectedChangedComponentCaller;
3560 void forEachFaceInstance(const BrushInstanceVisitor& visitor)
3562 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3568 static void constructStatic()
3570 m_state_selpoint = GlobalShaderCache().capture("$SELPOINT");
3572 static void destroyStatic()
3574 GlobalShaderCache().release("$SELPOINT");
3579 m_faceInstances.clear();
3581 void reserve(std::size_t size)
3583 m_faceInstances.reserve(size);
3586 void push_back(Face& face)
3588 m_faceInstances.push_back(FaceInstance(face, SelectedChangedComponentCaller(*this)));
3592 ASSERT_MESSAGE(!m_faceInstances.empty(), "erasing invalid element");
3593 m_faceInstances.pop_back();
3595 void erase(std::size_t index)
3597 ASSERT_MESSAGE(index < m_faceInstances.size(), "erasing invalid element");
3598 m_faceInstances.erase(m_faceInstances.begin() + index);
3600 void connectivityChanged()
3602 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3604 (*i).connectivityChanged();
3610 m_edgeInstances.clear();
3612 void edge_push_back(SelectableEdge& edge)
3614 m_edgeInstances.push_back(EdgeInstance(m_faceInstances, edge));
3619 m_vertexInstances.clear();
3621 void vertex_push_back(SelectableVertex& vertex)
3623 m_vertexInstances.push_back(VertexInstance(m_faceInstances, vertex));
3626 void DEBUG_verify() const
3628 ASSERT_MESSAGE(m_faceInstances.size() == m_brush.DEBUG_size(), "FATAL: mismatch");
3631 bool isSelected() const
3633 return m_selectable.isSelected();
3635 void setSelected(bool select)
3637 m_selectable.setSelected(select);
3640 void update_selected() const
3642 m_render_selected.clear();
3643 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3645 if((*i).getFace().contributes())
3647 (*i).iterate_selected(m_render_selected);
3652 void evaluateViewDependent(const VolumeTest& volume, const Matrix4& localToWorld) const
3656 m_viewChanged = false;
3658 bool faces_visible[c_brush_maxFaces];
3660 bool* j = faces_visible;
3661 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i, ++j)
3663 *j = (*i).intersectVolume(volume, localToWorld);
3667 m_brush.update_wireframe(m_render_wireframe, faces_visible);
3668 m_brush.update_faces_wireframe(m_faceCentroidPointsCulled, faces_visible);
3672 void renderComponentsSelected(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3674 m_brush.evaluateBRep();
3677 if(!m_render_selected.empty())
3679 renderer.Highlight(Renderer::ePrimitive, false);
3680 renderer.SetState(m_state_selpoint, Renderer::eWireframeOnly);
3681 renderer.SetState(m_state_selpoint, Renderer::eFullMaterials);
3682 renderer.addRenderable(m_render_selected, localToWorld);
3686 void renderComponents(Renderer& renderer, const VolumeTest& volume) const
3688 m_brush.evaluateBRep();
3690 const Matrix4& localToWorld = Instance::localToWorld();
3692 renderer.SetState(m_brush.m_state_point, Renderer::eWireframeOnly);
3693 renderer.SetState(m_brush.m_state_point, Renderer::eFullMaterials);
3695 if(volume.fill() && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace)
3697 evaluateViewDependent(volume, localToWorld);
3698 renderer.addRenderable(m_render_faces_wireframe, localToWorld);
3702 m_brush.renderComponents(GlobalSelectionSystem().ComponentMode(), renderer, volume, localToWorld);
3706 void renderClipPlane(Renderer& renderer, const VolumeTest& volume) const
3708 if(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip && isSelected())
3710 m_clipPlane.render(renderer, volume, localToWorld());
3714 void renderCommon(Renderer& renderer, const VolumeTest& volume) const
3716 bool componentMode = GlobalSelectionSystem().Mode() == SelectionSystem::eComponent;
3718 if(componentMode && isSelected())
3720 renderComponents(renderer, volume);
3723 if(parentSelected())
3727 renderer.Highlight(Renderer::eFace);
3729 renderer.Highlight(Renderer::ePrimitive);
3733 void renderSolid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3735 //renderCommon(renderer, volume);
3737 m_lightList->evaluateLights();
3739 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3741 renderer.setLights((*i).m_lights);
3742 (*i).render(renderer, volume, localToWorld);
3745 renderComponentsSelected(renderer, volume, localToWorld);
3748 void renderWireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3750 //renderCommon(renderer, volume);
3752 evaluateViewDependent(volume, localToWorld);
3754 if(m_render_wireframe.m_size != 0)
3756 renderer.addRenderable(m_render_wireframe, localToWorld);
3759 renderComponentsSelected(renderer, volume, localToWorld);
3762 void renderSolid(Renderer& renderer, const VolumeTest& volume) const
3764 m_brush.evaluateBRep();
3766 renderClipPlane(renderer, volume);
3768 renderSolid(renderer, volume, localToWorld());
3771 void renderWireframe(Renderer& renderer, const VolumeTest& volume) const
3773 m_brush.evaluateBRep();
3775 renderClipPlane(renderer, volume);
3777 renderWireframe(renderer, volume, localToWorld());
3780 void viewChanged() const
3782 m_viewChanged = true;
3785 void testSelect(Selector& selector, SelectionTest& test)
3787 test.BeginMesh(localToWorld());
3789 SelectionIntersection best;
3790 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3792 (*i).testSelect(test, best);
3796 selector.addIntersection(best);
3800 bool isSelectedComponents() const
3802 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3804 if((*i).selectedComponents())
3811 void setSelectedComponents(bool select, SelectionSystem::EComponentMode mode)
3813 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3815 (*i).setSelected(mode, select);
3818 void testSelectComponents(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode)
3820 test.BeginMesh(localToWorld());
3824 case SelectionSystem::eVertex:
3826 for(VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i)
3828 (*i).testSelect(selector, test);
3832 case SelectionSystem::eEdge:
3834 for(EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i)
3836 (*i).testSelect(selector, test);
3840 case SelectionSystem::eFace:
3842 if(test.getVolume().fill())
3844 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3846 (*i).testSelect(selector, test);
3851 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3853 (*i).testSelect_centroid(selector, test);
3863 void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback)
3865 test.BeginMesh(localToWorld());
3867 PlanePointer brushPlanes[c_brush_maxFaces];
3868 PlanesIterator j = brushPlanes;
3870 for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i)
3872 *j++ = &(*i)->plane3();
3875 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3877 (*i).selectPlane(selector, Line(test.getNear(), test.getFar()), brushPlanes, j, selectedPlaneCallback);
3880 void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes)
3882 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3884 (*i).selectReversedPlane(selector, selectedPlanes);
3889 void transformComponents(const Matrix4& matrix)
3891 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3893 (*i).transformComponents(matrix);
3896 const AABB& getSelectedComponentsBounds() const
3898 m_aabb_component = AABB();
3900 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3902 (*i).iterate_selected(m_aabb_component);
3905 return m_aabb_component;
3908 void snapComponents(float snap)
3910 for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3912 (*i).snapComponents(snap);
3915 void evaluateTransform()
3917 Matrix4 matrix(m_transform.calculateTransform());
3918 //globalOutputStream() << "matrix: " << matrix << "\n";
3920 if(m_transform.getType() == TRANSFORM_PRIMITIVE)
3922 m_brush.transform(matrix);
3926 transformComponents(matrix);
3929 void applyTransform()
3931 m_brush.revertTransform();
3932 evaluateTransform();
3933 m_brush.freezeTransform();
3935 typedef MemberCaller<BrushInstance, &BrushInstance::applyTransform> ApplyTransformCaller;
3937 void setClipPlane(const Plane3& plane)
3939 m_clipPlane.setPlane(m_brush, plane);
3942 bool testLight(const RendererLight& light) const
3944 return light.testAABB(worldAABB());
3946 void insertLight(const RendererLight& light)
3948 const Matrix4& localToWorld = Instance::localToWorld();
3949 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3951 Face_addLight(*i, localToWorld, light);
3956 for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3958 (*i).m_lights.clear();
3963 inline BrushInstance* Instance_getBrush(scene::Instance& instance)
3965 return InstanceTypeCast<BrushInstance>::cast(instance);
3969 template<typename Functor>
3970 class BrushSelectedVisitor : public SelectionSystem::Visitor
3972 const Functor& m_functor;
3974 BrushSelectedVisitor(const Functor& functor) : m_functor(functor)
3977 void visit(scene::Instance& instance) const
3979 BrushInstance* brush = Instance_getBrush(instance);
3987 template<typename Functor>
3988 inline void Scene_forEachSelectedBrush(const Functor& functor)
3990 GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor<Functor>(functor));
3993 template<typename Functor>
3994 class BrushVisibleSelectedVisitor : public SelectionSystem::Visitor
3996 const Functor& m_functor;
3998 BrushVisibleSelectedVisitor(const Functor& functor) : m_functor(functor)
4001 void visit(scene::Instance& instance) const
4003 BrushInstance* brush = Instance_getBrush(instance);
4005 && instance.path().top().get().visible())
4012 template<typename Functor>
4013 inline void Scene_forEachVisibleSelectedBrush(const Functor& functor)
4015 GlobalSelectionSystem().foreachSelected(BrushVisibleSelectedVisitor<Functor>(functor));