root/OpenSceneGraph/trunk/examples/osgtext3D/osgtext3D.cpp @ 11680

Revision 11680, 17.9 kB (checked in by robert, 4 years ago)

Added boundary bisector computation, bisector intersection thickness and segment removal.

Line 
1/* OpenSceneGraph example, osgtext.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#include <osg/ArgumentParser>
20#include <osg/Geode>
21#include <osg/Geometry>
22#include <osg/PositionAttitudeTransform>
23#include <osgText/Font3D>
24#include <osgDB/WriteFile>
25#include <osgGA/StateSetManipulator>
26#include <osgUtil/Tessellator>
27#include <osgViewer/Viewer>
28#include <osgViewer/ViewerEventHandlers>
29#include <osg/io_utils>
30
31extern int main_orig(int, char**);
32extern int main_test(int, char**);
33
34
35osg::Vec3 computeRayIntersectionPoint(const osg::Vec3& a, const osg::Vec3& an, const osg::Vec3& c, const osg::Vec3& cn)
36{
37    float denominator = ( cn.x() * an.y() - cn.y() * an.x());
38    if (denominator==0.0)
39    {
40        OSG_NOTICE<<"computeRayIntersectionPoint()<<denominator==0.0"<<std::endl;
41        // line segments must be parallel.
42        return (a+c)*0.5;
43    }
44
45    float t = ((a.x()-c.x())*an.y() - (a.y()-c.y())*an.x()) / denominator;
46    return c + cn*t;
47}
48
49osg::Vec3 computeIntersectionPoint(const osg::Vec3& a, const osg::Vec3& b, const osg::Vec3& c, const osg::Vec3& d)
50{
51#if 0
52    float ba_x = b.x()-a.x();
53    float ba_y = b.y()-a.y();
54
55    float dc_x = d.x()-c.x();
56    float dc_y = d.y()-c.y();
57
58    float denominator = (dc_x * ba_y - dc_y * ba_x);
59    if (denominator==0.0)
60    {
61        // line segments must be parallel.
62        return (b+c)*0.5;
63    }
64
65    float t = ((a.x()-c.x())*ba_y + (a.y()-c.y())*ba_x) / denominator;
66
67    return c + (d-c)*t;
68#endif
69    return computeRayIntersectionPoint(a, b-a, c, d-c);
70
71}
72
73osg::Vec3 computeBisectorNormal(const osg::Vec3& a, const osg::Vec3& b, const osg::Vec3& c, const osg::Vec3& d)
74{
75    osg::Vec2 ab(a.x()-b.x(), a.y()-b.y());
76    osg::Vec2 dc(d.x()-c.x(), d.y()-c.y());
77    float length_ab = ab.normalize();
78    float length_dc = dc.normalize();
79
80    float e = dc.y() - ab.y();
81    float f = ab.x() - dc.x();
82    float denominator = sqrtf(e*e + f*f);
83    float nx = e / denominator;
84    float ny = f / denominator;
85    if (( ab.x()*ny - ab.y()*nx) > 0.0f)
86    {
87        // OSG_NOTICE<<"   computeBisectorNormal(a=["<<a<<"], b=["<<b<<"], c=["<<c<<"], d=["<<d<<"]), nx="<<nx<<", ny="<<ny<<", denominator="<<denominator<<" no need to swap"<<std::endl;
88        return osg::Vec3(nx,ny,0.0f);
89    }
90    else
91    {
92        OSG_NOTICE<<"   computeBisectorNormal(a=["<<a<<"], b=["<<b<<"], c=["<<c<<"], d=["<<d<<"]), nx="<<nx<<", ny="<<ny<<", denominator="<<denominator<<" need to swap!!!"<<std::endl;
93        return osg::Vec3(-nx,-ny,0.0f);
94    }
95}
96
97float computeBisectorIntersectorThickness(const osg::Vec3& a, const osg::Vec3& b, const osg::Vec3& c, const osg::Vec3& d, const osg::Vec3& e, const osg::Vec3& f)
98{
99    osg::Vec3 intersection_abcd = computeIntersectionPoint(a,b,c,d);
100    osg::Vec3 bisector_abcd = computeBisectorNormal(a,b,c,d);
101    osg::Vec3 intersection_cdef = computeIntersectionPoint(c,d,e,f);
102    osg::Vec3 bisector_cdef = computeBisectorNormal(c,d,e,f);
103    if (bisector_abcd==bisector_cdef)
104    {
105        OSG_NOTICE<<"computeBisectorIntersector(["<<a<<"], ["<<b<<"], ["<<c<<"], ["<<d<<"], ["<<e<<"], ["<<f<<"[)"<<std::endl;
106        OSG_NOTICE<<"   bisectors parallel, thickness = "<<FLT_MAX<<std::endl;
107        return FLT_MAX;
108    }
109
110    osg::Vec3 bisector_intersection = computeRayIntersectionPoint(intersection_abcd,bisector_abcd, intersection_cdef, bisector_cdef);
111    osg::Vec3 normal(d.y()-c.y(), c.x()-d.x(), 0.0);
112    float cd_length = normal.normalize();
113    if (cd_length==0)
114    {
115        OSG_NOTICE<<"computeBisectorIntersector(["<<a<<"], ["<<b<<"], ["<<c<<"], ["<<d<<"], ["<<e<<"], ["<<f<<"[)"<<std::endl;
116        OSG_NOTICE<<"   segment length==0, thickness = "<<FLT_MAX<<std::endl;
117        return FLT_MAX;
118    }
119
120    float thickness = (bisector_intersection - c) * normal;
121#if 0
122    OSG_NOTICE<<"computeBisectorIntersector(["<<a<<"], ["<<b<<"], ["<<c<<"], ["<<d<<"], ["<<e<<"], ["<<f<<"[)"<<std::endl;
123    OSG_NOTICE<<"   bisector_abcd = "<<bisector_abcd<<", bisector_cdef="<<bisector_cdef<<std::endl;
124    OSG_NOTICE<<"   bisector_intersection = "<<bisector_intersection<<", thickness = "<<thickness<<std::endl;
125#endif
126    return thickness;
127}
128
129class Boundary
130{
131public:
132
133    typedef std::pair<unsigned int, unsigned int> Segment;
134    typedef std::vector<Segment>  Segments;
135    osg::ref_ptr<osg::Vec3Array> _vertices;
136    Segments _segments;
137
138    Boundary(osg::Vec3Array* vertices, unsigned int start, unsigned int count)
139    {
140        _vertices = vertices;
141
142        if ((*_vertices)[start]==(*_vertices)[start+count-1])
143        {
144            OSG_NOTICE<<"Boundary is a line loop"<<std::endl;
145        }
146        else
147        {
148            OSG_NOTICE<<"Boundary is not a line loop"<<std::endl;
149        }
150
151        _segments.reserve(count-1);
152        for(unsigned int i=start; i<start+count-1; ++i)
153        {
154            _segments.push_back(Segment(i,i+1));
155        }
156
157    }
158
159    float computeThickness(unsigned int i)
160    {
161        Segment& seg_before = _segments[ (i+_segments.size()-1) % _segments.size() ];
162        Segment& seg_target = _segments[ (i) % _segments.size() ];
163        Segment& seg_after =  _segments[ (i+1) % _segments.size() ];
164        return computeBisectorIntersectorThickness(
165            (*_vertices)[seg_before.first], (*_vertices)[seg_before.second],
166            (*_vertices)[seg_target.first], (*_vertices)[seg_target.second],
167            (*_vertices)[seg_after.first], (*_vertices)[seg_after.second]);
168    }
169
170    void computeAllThickness()
171    {
172        for(unsigned int i=0; i<_segments.size(); ++i)
173        {
174            computeThickness(i);
175        }
176    }
177
178
179    bool findMinThickness(unsigned int& minThickness_i, float& minThickness)
180    {
181        minThickness_i = _segments.size();
182        for(unsigned int i=0; i<_segments.size(); ++i)
183        {
184            float thickness = computeThickness(i);
185            if (thickness>0.0 && thickness <  minThickness)
186            {
187                minThickness = thickness;
188                minThickness_i = i;
189            }
190        }
191
192        return minThickness_i != _segments.size();
193    }
194
195    void removeAllSegmentsBelowThickness(float targetThickness)
196    {
197        OSG_NOTICE<<"removeAllSegmentsBelowThickness("<<targetThickness<<")"<<std::endl;
198        for(;;)
199        {
200            unsigned int minThickness_i = _segments.size();
201            float minThickness = targetThickness;
202            if (!findMinThickness(minThickness_i,minThickness)) break;
203
204            OSG_NOTICE<<"  removing segment _segments["<<minThickness_i<<"] ("<<_segments[minThickness_i].first<<", "<<_segments[minThickness_i].second<<" with thickness="<<minThickness<<" "<<std::endl;
205            _segments.erase(_segments.begin()+minThickness_i);
206        }
207    }
208
209};
210
211
212float computeAngle(osg::Vec3& v1, osg::Vec3& v2, osg::Vec3& v3)
213{
214    osg::Vec3 v12(v1-v2);
215    osg::Vec3 v32(v3-v2);
216    v12.normalize();
217    v32.normalize();
218    float dot = v12*v32;
219    float angle = acosf(dot);
220    return angle;
221}
222
223void computeBoundaryAngles(osg::Vec3Array& vertices, unsigned int start, unsigned int count)
224{
225    OSG_NOTICE<<"computeBoundaryAngles("<<vertices.size()<<", "<<start<<", "<<count<<")"<<std::endl;
226    if (vertices[start+count-1]==vertices[start])
227    {
228        OSG_NOTICE<<"is a line loop"<<std::endl;
229    }
230    else
231    {
232        OSG_NOTICE<<"is not line loop, ("<<vertices[start+count-1]<<"), ("<<vertices[start]<<")"<<std::endl;
233        return;
234    }
235
236    computeAngle(vertices[start+count-2],vertices[start],vertices[start+1]);
237    for(unsigned int i=start+1; i<start+count-1; ++i)
238    {
239        computeAngle(vertices[i-1],vertices[i],vertices[i+1]);
240    }
241    computeAngle(vertices[start+count-2],vertices[start],vertices[start+1]);
242}
243
244void computeBoundaryAngles(osg::Geometry* geometry)
245{
246    OSG_NOTICE<<"computeBoundaryAngles("<<geometry<<")"<<std::endl;
247    osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray());
248    osg::Geometry::PrimitiveSetList& primitives = geometry->getPrimitiveSetList();
249    for(osg::Geometry::PrimitiveSetList::iterator itr = primitives.begin();
250        itr != primitives.end();
251        ++itr)
252    {
253        osg::DrawArrays* drawArray = dynamic_cast<osg::DrawArrays*>(itr->get());
254        if (drawArray && drawArray->getMode()==GL_POLYGON)
255        {
256            computeBoundaryAngles(*vertices, drawArray->getFirst(), drawArray->getCount());
257        }
258    }
259}
260
261osg::Vec3 computeNewVertexPosition(osg::Vec3& v1, osg::Vec3& v2, osg::Vec3& v3)
262{
263    double angle = computeAngle(v1,v2,v3);
264    osg::Vec3 v21(v2-v1);
265    osg::Vec3 v32(v3-v2);
266    float length_21 = v21.normalize();
267    float length_32 = v32.normalize();
268
269    float t = 5.0;
270    if (length_21==0.0)
271    {
272        OSG_NOTICE<<"length_21=="<<length_21<<", length_32="<<length_32<<std::endl;
273        osg::Vec3 bisector = v32 ^ osg::Vec3(0.0f,0.0f,1.0f);
274        bisector.normalize();
275        osg::Vec3 new_vertex = v2 + bisector * t;
276        return new_vertex;
277    }
278    else if (length_32==0.0)
279    {
280        OSG_NOTICE<<"length_21=="<<length_21<<", length_32="<<length_32<<std::endl;
281        osg::Vec3 bisector = v21 ^ osg::Vec3(0.0f,0.0f,1.0f);
282        bisector.normalize();
283        osg::Vec3 new_vertex = v2 + bisector * t;
284        return new_vertex;
285    }
286
287    osg::Vec3 cross = v21^v32;
288    osg::Vec3 bisector(v32-v21);
289
290#if 0
291    OSG_NOTICE<<"v1=["<<v1<<"], v2=["<<v2<<"], v3=["<<v3<<"], dot_angle="<<osg::RadiansToDegrees(angle)<<std::endl;
292    OSG_NOTICE<<"     computeIntersectionPoint() point "<<computeIntersectionPoint(v1,v2,v2,v3)<<std::endl;
293#endif
294    // OSG_NOTICE<<"     computeBisectorNormal() normal "<<computeBisectorNormal(v1,v2,v2,v3)<<std::endl;
295   
296    if (bisector.length()<0.5)
297    {
298        // angle wider than 90 degrees so use side vectors as guide for angle to project along.
299        osg::Vec3 s21 = v21 ^ osg::Vec3(0.0f,0.0f,1.0f);
300        s21.normalize();
301
302        osg::Vec3 s32 = v32 ^ osg::Vec3(0.0f,0.0f,1.0f);
303        s32.normalize();
304
305        osg::Vec3 bisector(s21+s32);
306        bisector.normalize();
307
308       
309        if ((computeBisectorNormal(v1,v2,v2,v3)-bisector).length2()>0.001)
310        {
311            OSG_NOTICE<<"     WARNING 1 bisector disagree "<<bisector<<", s21=["<<s21<<"], s32=["<<s32<<"]"<<std::endl;
312        }
313        else
314        {
315#if 0
316            OSG_NOTICE<<"     bisector normal "<<bisector<<std::endl;
317#endif
318        }
319
320        float l = t / sin(angle*0.5);
321
322        osg::Vec3 new_vertex = v2 + bisector * l;
323        new_vertex.z() += 0.5f;
324
325        return new_vertex;
326    }
327    else
328    {
329        float l = t / sin(angle*0.5);
330
331        bisector.normalize();
332        if (cross.z()>0.0) bisector = -bisector;
333
334        if ((computeBisectorNormal(v1,v2,v2,v3)-bisector).length2()>0.001)
335        {
336            OSG_NOTICE<<"     WARNING 2 bisector disagree "<<bisector<<std::endl;
337        }
338        else
339        {
340#if 0
341            OSG_NOTICE<<"     bisector normal "<<bisector<<std::endl;
342#endif
343        }
344
345        osg::Vec3 new_vertex = v2 + bisector * l;
346        new_vertex.z() += 0.5f;
347        return new_vertex;
348    }
349}
350
351osg::DrawArrays* computeBevelEdge(osg::Vec3Array& orig_vertices, unsigned int start, unsigned int count, osg::Vec3Array& new_vertices)
352{
353
354    OSG_NOTICE<<"computeBevelEdge("<<orig_vertices.size()<<", "<<start<<", "<<count<<")"<<std::endl;
355    if (orig_vertices[start+count-1]==orig_vertices[start])
356    {
357        OSG_NOTICE<<"is a line loop"<<std::endl;
358    }
359    else
360    {
361        OSG_NOTICE<<"is not line loop, ("<<orig_vertices[start+count-1]<<"), ("<<orig_vertices[start]<<")"<<std::endl;
362        return new osg::DrawArrays(GL_POLYGON, start, count);
363    }
364
365    new_vertices[start] = computeNewVertexPosition(orig_vertices[start+count-2],orig_vertices[start],orig_vertices[start+1]);
366    for(unsigned int i=start+1; i<start+count-1; ++i)
367    {
368        new_vertices[i] = computeNewVertexPosition(orig_vertices[i-1],orig_vertices[i],orig_vertices[i+1]);
369    }
370    new_vertices[start+count-1] = computeNewVertexPosition(orig_vertices[start+count-2],orig_vertices[start],orig_vertices[start+1]);
371
372    return new osg::DrawArrays(GL_POLYGON, start, count);
373}
374
375void removeLoops(osg::Vec3Array& orig_vertices, unsigned int start, unsigned int count)
376{
377}
378
379osg::Geometry* computeBevelEdge(osg::Geometry* orig_geometry)
380{
381    OSG_NOTICE<<"computeBoundaryAngles("<<orig_geometry<<")"<<std::endl;
382    osg::Vec3Array* orig_vertices = dynamic_cast<osg::Vec3Array*>(orig_geometry->getVertexArray());
383    osg::Geometry::PrimitiveSetList& orig_primitives = orig_geometry->getPrimitiveSetList();
384
385    osg::Geometry* new_geometry = new osg::Geometry;
386    osg::Vec3Array* new_vertices = new osg::Vec3Array(*orig_vertices);
387    osg::Geometry::PrimitiveSetList& new_primitives = new_geometry->getPrimitiveSetList();
388    new_geometry->setVertexArray(new_vertices);
389    osg::Vec4Array* new_colours = new osg::Vec4Array;
390    new_colours->push_back(osg::Vec4(1.0,0.0,0.0,1.0));
391    new_geometry->setColorArray(new_colours);
392    new_geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
393
394    for(osg::Geometry::PrimitiveSetList::iterator itr = orig_primitives.begin();
395        itr != orig_primitives.end();
396        ++itr)
397    {
398        osg::DrawArrays* drawArray = dynamic_cast<osg::DrawArrays*>(itr->get());
399        if (drawArray && drawArray->getMode()==GL_POLYGON)
400        {
401            osg::DrawArrays* new_drawArray = computeBevelEdge(*orig_vertices, drawArray->getFirst(), drawArray->getCount(), *new_vertices);
402            removeLoops(*new_vertices, new_drawArray->getFirst(), new_drawArray->getCount());
403            new_primitives.push_back(new_drawArray);
404        }
405    }
406    return new_geometry;
407}
408
409osg::Geometry* computeThickness(osg::Geometry* orig_geometry, float thickness)
410{
411    OSG_NOTICE<<"computeThickness("<<orig_geometry<<")"<<std::endl;
412    osg::Vec3Array* orig_vertices = dynamic_cast<osg::Vec3Array*>(orig_geometry->getVertexArray());
413    osg::Geometry::PrimitiveSetList& orig_primitives = orig_geometry->getPrimitiveSetList();
414
415    for(osg::Geometry::PrimitiveSetList::iterator itr = orig_primitives.begin();
416        itr != orig_primitives.end();
417        ++itr)
418    {
419        osg::DrawArrays* drawArray = dynamic_cast<osg::DrawArrays*>(itr->get());
420        if (drawArray && drawArray->getMode()==GL_POLYGON)
421        {
422            Boundary boundary(orig_vertices, drawArray->getFirst(), drawArray->getCount());
423            boundary.computeAllThickness();
424
425            boundary.removeAllSegmentsBelowThickness(thickness);
426        }
427    }
428    return 0;
429}
430
431
432int main(int argc, char** argv)
433{
434    osg::ArgumentParser arguments(&argc, argv);
435
436    if (arguments.read("--test"))
437    {
438        return main_test(argc,argv);
439    }
440    else if (arguments.read("--original") || arguments.read("--orig"))
441    {
442        return main_orig(argc,argv);
443    }
444
445    std::string fontFile("arial.ttf");
446    while(arguments.read("-f",fontFile)) {}
447
448    std::string word("This is a simple test");
449    while(arguments.read("-w",word)) {}
450
451    osg::ref_ptr<osgText::Font3D> font = osgText::readFont3DFile(fontFile);
452    if (!font) return 1;
453    OSG_NOTICE<<"Read font "<<fontFile<<" font="<<font.get()<<std::endl;
454
455
456    bool useTessellator = false;
457    while(arguments.read("-t") || arguments.read("--tessellate")) { useTessellator = true; }
458
459    float thickness = 5.0;
460    while(arguments.read("--thickness",thickness)) {}
461
462    osg::ref_ptr<osg::Group> group = new osg::Group;
463    osg::Vec3 position;
464
465    for(unsigned int i=0; i<word.size(); ++i)
466    {
467        osg::ref_ptr<osgText::Font3D::Glyph3D> glyph = font->getGlyph(word[i]);
468        if (!glyph) return 1;
469
470        osg::ref_ptr<osg::PositionAttitudeTransform> transform = new osg::PositionAttitudeTransform;
471        transform->setPosition(position);
472        transform->setAttitude(osg::Quat(osg::inDegrees(90.0),osg::Vec3d(1.0,0.0,0.0)));
473
474        position.x() += glyph->getHorizontalWidth();
475
476        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
477
478        osg::Vec3Array* vertices = glyph->getRawVertexArray();
479        osg::Geometry::PrimitiveSetList& primitives = glyph->getRawFacePrimitiveSetList();
480
481        osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry;
482        geometry->setVertexArray(vertices);
483        geometry->setPrimitiveSetList(primitives);
484        osg::Vec4Array* colours = new osg::Vec4Array;
485        colours->push_back(osg::Vec4(1.0,1.0,1.0,1.0));
486        geometry->setColorArray(colours);
487        geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
488
489        // computeBoundaryAngles(geometry);
490
491        osg::Geometry* bevel = computeBevelEdge(geometry);
492        geode->addDrawable(bevel);
493
494        computeThickness(geometry, thickness);
495
496        if (useTessellator)
497        {
498            osgUtil::Tessellator ts;
499            ts.setWindingType(osgUtil::Tessellator::TESS_WINDING_POSITIVE);
500            ts.setTessellationType(osgUtil::Tessellator::TESS_TYPE_GEOMETRY);
501            ts.retessellatePolygons(*geometry);
502
503            ts.retessellatePolygons(*bevel);
504
505        }
506
507        geode->addDrawable(geometry.get());
508
509        transform->addChild(geode.get());
510
511        group->addChild(transform.get());
512    }
513
514    std::string filename;
515    if (arguments.read("-o", filename)) osgDB::writeNodeFile(*group, filename);
516
517    osgViewer::Viewer viewer(arguments);
518    viewer.setSceneData(group.get());
519    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
520    return viewer.run();
521}
Note: See TracBrowser for help on using the browser.