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40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-    */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */

/*

  Author(s):  Anton Deguet
  Created on: 2008-06-10

  (C) Copyright 2008 Johns Hopkins University (JHU), All Rights
  Reserved.

--- begin cisst license - do not edit ---

This software is provided "as is" under an open source license, with
no warranty.  The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.

--- end cisst license ---
*/


#include <cisst3DUserInterface/ui3Widget3D.h>
#include <cisst3DUserInterface/ui3SceneManager.h>
#include <cisst3DUserInterface/ui3VisibleList.h>
#include <cisst3DUserInterface/ui3MasterArm.h>

#include <vtkActor.h>
#include <vtkAssembly.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkSphereSource.h>

CMN_IMPLEMENT_SERVICES(ui3Widget3DHandle);

ui3Widget3DHandle::ui3Widget3DHandle(unsigned int handleNumber,
                                     ui3Widget3D * widget3D):
    ui3Selectable("ui3Widget3DHandle"),
    HandleNumber(handleNumber),
    Widget3D(widget3D),
    Source(0),
    Mapper(0),
    Actor(0)
{}


ui3Widget3DHandle::~ui3Widget3DHandle()
{
    if (this->Source) {
        this->Source->Delete();
    }

    if (this->Mapper) {
        this->Mapper->Delete();
    }

    if (this->Actor) {
        this->Actor->Delete();
    }
}


bool ui3Widget3DHandle::CreateVTKObjects(void)
{
    this->Source = vtkSphereSource::New();
    CMN_ASSERT(this->Source);
    this->Source->SetRadius(0.5);

    this->Mapper = vtkPolyDataMapper::New();
    CMN_ASSERT(this->Mapper);
    this->Mapper->SetInputConnection(this->Source->GetOutputPort());
    this->Mapper->ImmediateModeRenderingOn();

    this->Actor = vtkActor::New();
    CMN_ASSERT(this->Actor);
    this->Actor->SetMapper(this->Mapper);

    this->AddPart(this->Actor);
    return true;
}


void ui3Widget3DHandle::UpdateColor(bool selected)
{
#if 0
    if (this->Created()) {
        this->Lock();
        if (selected) {
            this->Actor->GetProperty()->SetOpacity(1.0);
        } else {
            this->Actor->GetProperty()->SetOpacity(1.0);
        }
        this->Unlock();
    }
#endif
}


void ui3Widget3DHandle::ShowIntention(void)
{
    if (this->Created()) {
        // this->Lock();
        if (this->Selected()) {
            this->Actor->GetProperty()->SetOpacity(1.0);
            this->Actor->GetProperty()->SetColor(0.0, 1.0, 0.0);
        } else {
            //            this->Actor->GetProperty()->SetOpacity(0.5 + (this->OverallIntention * 0.5));
            this->Actor->GetProperty()->SetOpacity(1.0);
            this->Actor->GetProperty()->SetColor(1.0, 1.0 - this->OverallIntention, 1.0 - this->OverallIntention);
        }
        // this->Unlock();
    }
}


double ui3Widget3DHandle::GetIntention(const vctFrm3 & cursorPosition) const
{
    vctDouble3 difference;
    difference.DifferenceOf(cursorPosition.Translation(), this->GetAbsoluteTransformation().Translation());
    difference.Z() /= 3.0;
    double distance = difference.Norm();
    const double threshold = 5.0; // in mm
    if (distance > threshold) {
        return 0.0;
    } else {
        return (1.0 - (distance / threshold)); // normalized between 0 and 1
    }
}




CMN_IMPLEMENT_SERVICES(ui3Widget3D);


ui3Widget3D::ui3Widget3D(const std::string & name):
    BaseType(name + "-3DWidget"),
    UserObjects(0),
    Handles(0),
    PreviousFirstSideHandle(-1),
    PreviousSecondSideHandle(-1),
    PreviousCornerHandle(-1)
{
    this->UserObjects = new ui3VisibleList(this->Name() + "[user objects]");
    CMN_ASSERT(this->UserObjects);
    BaseType::Add(this->UserObjects);

    this->Handles = new ui3VisibleList(this->Name() + "[handles]");
    CMN_ASSERT(this->Handles);
    BaseType::Add(this->Handles);

    // create handles to be used and add them to base class list
    unsigned int handleCounter;
    ui3Widget3DHandle * handle;
    for (handleCounter = 0;
         handleCounter < 4;
         handleCounter++) {
        handle = new ui3Widget3DHandle(handleCounter, this);
        CMN_ASSERT(handle);
        this->Handles->Add(handle);
        this->SideHandles[handleCounter] = handle;
    }
    for (handleCounter = 0;
         handleCounter < 4;
         handleCounter++) {
        handle = new ui3Widget3DHandle(handleCounter, this);
        CMN_ASSERT(handle);
        this->Handles->Add(handle);
        this->CornerHandles[handleCounter] = handle;
    }

    // set handles as active
    this->SetHandlesActive(true);
}


bool ui3Widget3D::Add(ui3VisibleObject * object)
{
    CMN_ASSERT(this->UserObjects);
    return this->UserObjects->Add(object);
}


void ui3Widget3D::SetSize(double halfSize)
{
    this->SetHandlesSpacing(halfSize);
    unsigned int handleCounter;
    vctDouble3 position;

    const short sides[5] = {-1, 0, 1, 0, -1};
    const short corners[5] = {-1, -1, 1, 1, -1};
    for (handleCounter = 0;
         handleCounter < 4;
         handleCounter++) {
        position.Assign(sides[handleCounter] * halfSize, sides[handleCounter + 1] * halfSize, 0.0);
        CMN_LOG_CLASS_RUN_DEBUG << "SetSize: set side handle at: " << position << std::endl;
        CMN_ASSERT(this->SideHandles[handleCounter]);
        this->SideHandles[handleCounter]->SetPosition(position);
        position.Assign(corners[handleCounter] * halfSize, corners[handleCounter + 1] * halfSize, 0.0);
        CMN_LOG_CLASS_RUN_DEBUG << "SetSize: set corner handle at: " << position << std::endl;
        CMN_ASSERT(this->CornerHandles[handleCounter]);
        this->CornerHandles[handleCounter]->SetPosition(position);
    }
}


void ui3Widget3D::SetHandlesActive(bool handlesActive)
{
    this->HandlesActiveMember = handlesActive;
    unsigned int handleCounter;

    if (this->HandlesActive()) {
        for (handleCounter = 0;
             handleCounter < 4;
             handleCounter++) {
            this->SideHandles[handleCounter]->SetActivated(true);
            this->CornerHandles[handleCounter]->SetActivated(true);
        }
    } else {
        for (handleCounter = 0;
             handleCounter < 4;
             handleCounter++) {
            this->SideHandles[handleCounter]->SetActivated(false);
            this->CornerHandles[handleCounter]->SetActivated(false);
        }
    }
}


void ui3Widget3D::UpdatePosition(void)
{
    unsigned int handleCounter;
    int firstSideHandle = -1; // invalid number
    int secondSideHandle = -1; // invalid number
    int cornerHandle = -1; // invalid number

    // figure out which handles are used
    for (handleCounter = 0;
         handleCounter < 4;
         handleCounter++) {
        if (this->SideHandles[handleCounter]->Selected()) {
            // save the handle index
            if (firstSideHandle == -1) {
                firstSideHandle = handleCounter;
            } else {
                secondSideHandle = handleCounter;
            }
        }
        if (this->CornerHandles[handleCounter]->Selected()) {
            // save the handle index
            cornerHandle = handleCounter;
        }
    }
    // sanity check, corner always prevails
    if (cornerHandle != -1) {
        firstSideHandle = -1;
        secondSideHandle = -1;
    }

    // test for transition, should re-activate all handles
    if ((firstSideHandle != this->PreviousFirstSideHandle)
        || (secondSideHandle != this->PreviousSecondSideHandle)
        || (cornerHandle != this->PreviousCornerHandle)) {
        // no handle selected, re-activate all
        if ((firstSideHandle == -1) && (cornerHandle == -1)) {
            this->SetHandlesActive(true);
            // apply last known transformation to whole widget but keep the handles in place
            //vctFrm3 newPosition;
            //newPosition.Assign(this->GetTransformation());
            //this->SetTransformation(newPosition, false);
            //this->UserObjects->SetTransformation(vctFrm3::Identity(), false);
            //this->Handles->SetPosition(vct3(0.0));
            //this->Handles->SetOrientation(newPosition.Rotation().InverseSelf(), false);
            // this->Handles->SetTransformation(vctFrm3::Identity(), false);
            // this->PositionBeforeManipulation.Assign(this->GetAbsoluteTransformation());
        } else if ((secondSideHandle == -1) && (cornerHandle == -1)){
            // de-activate all but the one opposite direction of selected side handle
            this->SetHandlesActive(false);
            this->SideHandles[(firstSideHandle + 2) % 4]->Show();
            this->SideHandles[(firstSideHandle + 2) % 4]->SetActivated(true);
        } else {
            // de-activate all
            this->SetHandlesActive(false);
        }
    }

    // do the actual computation if needed
    if (cornerHandle != -1) {
        vctDouble3 translation, translationInWorld;
        translation.DifferenceOf(this->CornerHandles[cornerHandle]->CurrentPosition.Translation(),
                                 this->CornerHandles[cornerHandle]->PreviousPosition.Translation());
        this->GetTransformation().Rotation().ApplyInverseTo(translation, translationInWorld);
        CurrentTransformation.Translation().Assign(translationInWorld);
        CurrentTransformation.Rotation().Assign(vctFrm3::RotationType::Identity());

        // apply last known transformation to whole widget but keep the handles in place
        vctFrm3 newPosition;
        this->GetTransformation().ApplyTo(this->CurrentTransformation, newPosition);
        this->SetTransformation(newPosition, false);
        // this->UserObjects->SetTransformation(vctFrm3::Identity(), false);
        this->Handles->SetPosition(vct3(0.0));
        this->Handles->SetOrientation(newPosition.Rotation().InverseSelf(), false);
    }
    if (firstSideHandle != -1) {
        vctDouble3 axis;
        double angle;
        axis.Assign(1.0,0.0,0.0);
        angle = 0.0;

        if (secondSideHandle == -1) {
            /*
            // one handed manipulation

            // get handle displacement
            vctDouble3 center, initial, current;
            center.Assign(this->GetAbsoluteTransformation().Translation());
            initial.DifferenceOf(this->SideHandles[firstSideHandle]->PreviousPosition.Translation(),
            center);
            initial.NormalizedSelf();
            current.DifferenceOf(this->SideHandles[firstSideHandle]->CurrentPosition.Translation(),
            center);
            current.NormalizedSelf();

            double initialAngle, currentAngle;
            // rotation along Y
            if ((firstSideHandle == 0) || (firstSideHandle == 2)) {
            initialAngle = atan2(initial.X(), initial.Z());
            currentAngle = atan2(current.X(), current.Z());
            angle = currentAngle - initialAngle;
            axis.Assign(0.0, 1.0, 0.0);
            } else {
            // rotation along X
            initialAngle = atan2(initial.Y(), initial.Z());
            currentAngle = atan2(current.Y(), current.Z());
            angle = initialAngle - currentAngle;
            axis.Assign(1.0, 0.0, 0.0);
            }
            */
        } else {
            // two handed manipulation
            //std::cerr << "Two handles manipulation not yet implemented. Why" << std::endl;
            double object_displacement[3], object_rotation[4];
            ComputeTransform(this->SideHandles[firstSideHandle]->PreviousPosition.Translation().Pointer(),
                             this->SideHandles[secondSideHandle]->PreviousPosition.Translation().Pointer(),
                             this->SideHandles[firstSideHandle]->CurrentPosition.Translation().Pointer(),
                             this->SideHandles[secondSideHandle]->CurrentPosition.Translation().Pointer(),
                             object_displacement, object_rotation);

            // Set the Translation.
            vctDouble3 translation, translationInWorld;
            translation.Assign(object_displacement);
            this->GetTransformation().Rotation().ApplyInverseTo(translation, translationInWorld);
            CurrentTransformation.Translation().Assign(translationInWorld);

            // Set the Rotation.
            angle = object_rotation[0];
            axis.Assign(object_rotation+1);
            vctDouble3 axisInWorld;
            this->GetTransformation().Rotation().ApplyInverseTo(axis, axisInWorld);
            CurrentTransformation.Rotation().From(vctAxAnRot3(axisInWorld, angle));

            // apply last known transformation to whole widget but keep the handles in place
            vctFrm3 newPosition;
            this->GetTransformation().ApplyTo(this->CurrentTransformation, newPosition);
            this->SetTransformation(newPosition, false);
            // this->UserObjects->SetTransformation(vctFrm3::Identity(), false);
            this->Handles->SetPosition(vct3(0.0));
            this->Handles->SetOrientation(newPosition.Rotation().InverseSelf(), false);
        }
    }

    this->PreviousFirstSideHandle = firstSideHandle;
    this->PreviousSecondSideHandle = secondSideHandle;
    this->PreviousCornerHandle = cornerHandle;
}


/*--------------------------------------------------------------------------------------*/


/*!
  Compute the object transform from the motion of two grabbed control points.
  @param pointa               Right control position.
  @param pointb               Left control position.
  @param point1               Right cursor pos.
  @param point2               Left cursor pos.
  @param object_displacement  [dx, dy, dz]
  @param object_rotation      [angle, axis_x, axis_y, axis_z]
*/
void ui3Widget3D::ComputeTransform(double pointa[3], double pointb[3],
                                   double point1[3], double point2[3],
                                   double object_displacement[3],
                                   double object_rotation[4])
{
    double v1[3], v2[3], v1norm, v2norm, wnorm;
    double w[3], angle, dotarg;

    //cout << "pointa: " << pointa[0] << " " << pointa[1] << " " << pointa[2] << endl;
    //cout << "pointb: " << pointb[0] << " " << pointb[1] << " " << pointb[2] << endl;

    // v1 = ((pb-pa)/norm(pb-pa))
    v1[0] = pointb[0]-pointa[0];
    v1[1] = pointb[1]-pointa[1];
    v1[2] = pointb[2]-pointa[2];
    v1norm = sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]);
    if(v1norm>cmnTypeTraits<double>::Tolerance())
        {
            v1[0] /= v1norm;
            v1[1] /= v1norm;
            v1[2] /= v1norm;
        }

    // v2 = ((p2-p1)/norm(p2-p1))
    v2[0] = point2[0]-point1[0];
    v2[1] = point2[1]-point1[1];
    v2[2] = point2[2]-point1[2];
    v2norm = sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2]);
    if(v2norm>cmnTypeTraits<double>::Tolerance())
        {
            v2[0] /= v2norm;
            v2[1] /= v2norm;
            v2[2] /= v2norm;
        }

    // w = (v1 x v2)/norm(v1 x v2)
    w[0] = v1[1]*v2[2] - v1[2]*v2[1];
    w[1] = v1[2]*v2[0] - v1[0]*v2[2];
    w[2] = v1[0]*v2[1] - v1[1]*v2[0];
    wnorm = sqrt(w[0]*w[0]+w[1]*w[1]+w[2]*w[2]);
    if(wnorm> cmnTypeTraits<double>::Tolerance())
        {
            w[0] /= wnorm;
            w[1] /= wnorm;
            w[2] /= wnorm;
        }
    else {
        w[0] = 1.0;
        w[1] = w[2] = 0.0;
    }

    // theta = arccos(v1.v2/(norm(v1)*norm(v2))
    dotarg = v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2];
    if(dotarg>-1.0 && dotarg<1.0)
        angle = acos(dotarg);
    else
        angle = 0.0;
    //if(CMN_ISNAN(angle)) angle=0.0;

    cout << "v1: " << v1[0] << " " << v1[1] << " " << v1[2] << endl;
    cout << "v2: " << v2[0] << " " << v2[1] << " " << v2[2] << endl;
    cout << "w: " << w[0] << " " << w[1] << " " << w[2] << " angle: " << angle*180.0/cmnPI << endl;

    // Set object pose updates.
    object_displacement[0] = (point1[0]+point2[0])/2 - (pointa[0]+pointb[0])/2;
    object_displacement[1] = (point1[1]+point2[1])/2 - (pointa[1]+pointb[1])/2;
    object_displacement[2] = (point1[2]+point2[2])/2 - (pointa[2]+pointb[2])/2;

    object_rotation[0] = angle;
    object_rotation[1] = w[0];
    object_rotation[2] = w[1];
    object_rotation[3] = w[2];
}

/*--------------------------------------------------------------------------------------*/