Skip to content
Snippets Groups Projects
mesh_carver.py 140 KiB
Newer Older
  • Learn to ignore specific revisions
  •                     DrawLeftText("[Alt]", xHelp, yHelp - Help_Interval, Help_FontSize, UIColor, self)
                        DrawLeftText("[" + context.scene.Key_Subrem + "] [" + context.scene.Key_Subadd + "]",
                                     xHelp, yHelp - Help_Interval * 2, Help_FontSize, UIColor, self)
                        DrawLeftText("[Ctrl]", xHelp, yHelp - Help_Interval * 3, Help_FontSize, UIColor, self)
    
                        DrawLeftText("[" + context.scene.Key_Solver + "]", xHelp, yHelp - Help_Interval * 4, Help_FontSize, UIColor, self)
    
                        DrawLeftText(": Rotation and Radius", 150 + t_panel_width, yHelp, Help_FontSize, None, self)
                        DrawLeftText(": Move all", 150 + t_panel_width, yHelp - Help_Interval, Help_FontSize, None, self)
                        DrawLeftText(": Subdivision", 150 + t_panel_width, yHelp -
                                     Help_Interval * 2, Help_FontSize, None, self)
                        DrawLeftText(": Incremental rotation", 150 + t_panel_width,
                                     yHelp - Help_Interval * 3, Help_FontSize, None, self)
    
                        DrawLeftText(": Solver [" + context.scene.CarverSolver + "]", 150 + t_panel_width, yHelp - Help_Interval * 4, Help_FontSize, None, self)
    
    
                    if self.CutMode == LINE:
                        DrawLeftText("MouseMove", xHelp, yHelp, Help_FontSize, UIColor, self)
                        DrawLeftText("[Alt]", xHelp, yHelp - Help_Interval, Help_FontSize, UIColor, self)
                        DrawLeftText("[Space]", xHelp, yHelp - Help_Interval * 2, Help_FontSize, UIColor, self)
                        DrawLeftText("[Ctrl]", xHelp, yHelp - Help_Interval * 3, Help_FontSize, UIColor, self)
    
                        DrawLeftText("[" + context.scene.Key_Solver + "]", xHelp, yHelp - Help_Interval * 4, Help_FontSize, UIColor, self)
    
                        DrawLeftText(": Dimension", 150 + t_panel_width, yHelp, Help_FontSize, None, self)
                        DrawLeftText(": Move all", 150 + t_panel_width, yHelp - Help_Interval, Help_FontSize, None, self)
                        DrawLeftText(": Validate", 150 + t_panel_width, yHelp -
                                     Help_Interval * 2, Help_FontSize, None, self)
                        DrawLeftText(": Incremental", 150 + t_panel_width, yHelp -
                                     Help_Interval * 3, Help_FontSize, None, self)
    
                        DrawLeftText(": Solver [" + context.scene.CarverSolver + "]", 150 + t_panel_width, yHelp - Help_Interval * 4, Help_FontSize, None, self)
    
                        if self.CreateMode:
                            DrawLeftText("[" + context.scene.Key_Subadd + "]", xHelp, yHelp -
                                         Help_Interval * 4, Help_FontSize, UIColor, self)
                            DrawLeftText(": Close geometry", 150 + t_panel_width, yHelp -
                                         Help_Interval * 4, Help_FontSize, None, self)
                else:
                    DrawLeftText("[Space]", xHelp, yHelp + Help_Interval, Help_FontSize, UIColor, self)
                    DrawLeftText(": Difference", 150 + t_panel_width, yHelp + Help_Interval, Help_FontSize, None, self)
                    DrawLeftText("[Shift][Space]", xHelp, yHelp, Help_FontSize, UIColor, self)
                    DrawLeftText(": Rebool", 150 + t_panel_width, yHelp, Help_FontSize, None, self)
                    DrawLeftText("[Alt][Space]", xHelp, yHelp - Help_Interval, Help_FontSize, UIColor, self)
                    DrawLeftText(": Duplicate", 150 + t_panel_width, yHelp - Help_Interval, Help_FontSize, None, self)
                    DrawLeftText("[" + context.scene.Key_Scale + "]", xHelp, yHelp -
                                 Help_Interval * 2, Help_FontSize, UIColor, self)
                    DrawLeftText(": Scale", 150 + t_panel_width, yHelp - Help_Interval * 2, Help_FontSize, None, self)
                    DrawLeftText("[LMB][Move]", xHelp, yHelp - Help_Interval * 3, Help_FontSize, UIColor, self)
                    DrawLeftText(": Rotation", 150 + t_panel_width, yHelp - Help_Interval * 3, Help_FontSize, None, self)
                    DrawLeftText("[Ctrl][LMB][Move]", xHelp, yHelp - Help_Interval * 4, Help_FontSize, UIColor, self)
                    DrawLeftText(": Step Angle", 150 + t_panel_width, yHelp - Help_Interval * 4, Help_FontSize, None, self)
                    if self.ProfileMode:
                        DrawLeftText("[" + context.scene.Key_Subadd + "][" + context.scene.Key_Subrem + "]",
                                     xHelp, yHelp - Help_Interval * 5, Help_FontSize, UIColor, self)
                        DrawLeftText(": Previous or Next Profile", 150 + t_panel_width,
                                     yHelp - Help_Interval * 5, Help_FontSize, None, self)
                    DrawLeftText("[ARROWS]", xHelp, yHelp - Help_Interval * 6, Help_FontSize, UIColor, self)
                    DrawLeftText(": Create / Delete rows or columns", 150 + t_panel_width,
                                 yHelp - Help_Interval * 6, Help_FontSize, None, self)
                    DrawLeftText("[" + context.scene.Key_Gapy + "][" + context.scene.Key_Gapx + "]",
                                 xHelp, yHelp - Help_Interval * 7, Help_FontSize, UIColor, self)
                    DrawLeftText(": Gap between rows or columns", 150 + t_panel_width,
                                 yHelp - Help_Interval * 7, Help_FontSize, None, self)
    
                    DrawLeftText("[" + context.scene.Key_Solver + "]", xHelp, yHelp - Help_Interval * 8, Help_FontSize, UIColor, self)
                    DrawLeftText(": Solver [" + context.scene.CarverSolver + "]", 150 + t_panel_width, yHelp - Help_Interval * 8, Help_FontSize, None, self)
    
    
        # Opengl Initialise
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.512, 0.919, 0.04, 1.0)
        bgl.glLineWidth(2)
    
    
        # if context.space_data.region_3d.is_perspective == False:
    
        if 1:
            bgl.glEnable(bgl.GL_POINT_SMOOTH)
    
            bgl.glPointSize(6)
    
            if self.ProfileMode:
                xrect = region.width - t_panel_width - 80
                yrect = 80
                bgl.glColor4f(0.0, 0.0, 0.0, 0.3)
                bgl.glRecti(xrect, yrect, xrect + 60, yrect - 60)
    
                faces = self.Profils[self.nProfil][3]
                vertices = self.Profils[self.nProfil][2]
                WidthProfil = 50
                location = mathutils.Vector((region.width - t_panel_width - WidthProfil, 50, 0))
                ProfilScale = 20.0
                bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 0.7)
                for f in faces:
                    if len(f) == 4:
                        bgl.glBegin(bgl.GL_QUADS)
                        bgl.glVertex3f(vertices[f[0]][0] * ProfilScale + location.x, vertices[f[0]][1]
                                       * ProfilScale + location.y, vertices[f[0]][2] * ProfilScale + location.z)
                        bgl.glVertex3f(vertices[f[1]][0] * ProfilScale + location.x, vertices[f[1]][1]
                                       * ProfilScale + location.y, vertices[f[1]][2] * ProfilScale + location.z)
                        bgl.glVertex3f(vertices[f[2]][0] * ProfilScale + location.x, vertices[f[2]][1]
                                       * ProfilScale + location.y, vertices[f[2]][2] * ProfilScale + location.z)
                        bgl.glVertex3f(vertices[f[3]][0] * ProfilScale + location.x, vertices[f[3]][1]
                                       * ProfilScale + location.y, vertices[f[3]][2] * ProfilScale + location.z)
                        bgl.glEnd()
                    if len(f) == 3:
                        bgl.glBegin(bgl.GL_TRIANGLES)
                        bgl.glVertex3f(vertices[f[0]][0] * ProfilScale + location.x, vertices[f[0]][1]
                                       * ProfilScale + location.y, vertices[f[0]][2] * ProfilScale + location.z)
                        bgl.glVertex3f(vertices[f[1]][0] * ProfilScale + location.x, vertices[f[1]][1]
                                       * ProfilScale + location.y, vertices[f[1]][2] * ProfilScale + location.z)
                        bgl.glVertex3f(vertices[f[2]][0] * ProfilScale + location.x, vertices[f[2]][1]
                                       * ProfilScale + location.y, vertices[f[2]][2] * ProfilScale + location.z)
                        bgl.glEnd()
    
            if self.bDone:
                if len(self.mouse_path) > 1:
                    x0 = self.mouse_path[0][0]
                    y0 = self.mouse_path[0][1]
                    x1 = self.mouse_path[1][0]
                    y1 = self.mouse_path[1][1]
    
                # Cut Line
                if self.CutMode == LINE:
                    if (self.shift) or (self.CreateMode and self.Closed):
                        bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 0.5)
    
                        bgl.glBegin(bgl.GL_POLYGON)
                        for x, y in self.mouse_path:
                            bgl.glVertex2i(x + self.xpos, y + self.ypos)
                        bgl.glEnd()
    
                    bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 1.0)
                    bgl.glBegin(bgl.GL_LINE_STRIP)
                    for x, y in self.mouse_path:
                        bgl.glVertex2i(x + self.xpos, y + self.ypos)
                    bgl.glEnd()
                    if (self.CreateMode == False) or (self.CreateMode and self.Closed):
                        bgl.glBegin(bgl.GL_LINE_STRIP)
                        bgl.glVertex2i(self.mouse_path[len(self.mouse_path) - 1][0] + self.xpos,
                                       self.mouse_path[len(self.mouse_path) - 1][1] + self.ypos)
                        bgl.glVertex2i(self.mouse_path[0][0] + self.xpos, self.mouse_path[0][1] + self.ypos)
                        bgl.glEnd()
    
                    bgl.glPointSize(6)
                    bgl.glBegin(bgl.GL_POINTS)
                    for x, y in self.mouse_path:
                        bgl.glVertex2i(x + self.xpos, y + self.ypos)
                    bgl.glEnd()
    
                # Cut rectangle
                if self.CutMode == RECTANGLE:
                    bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 0.5)
    
                    # if SHIFT, fill primitive
                    if self.shift or self.CreateMode:
                        bgl.glBegin(bgl.GL_QUADS)
                        bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
                        bgl.glVertex2i(x1 + self.xpos, y0 + self.ypos)
                        bgl.glVertex2i(x1 + self.xpos, y1 + self.ypos)
                        bgl.glVertex2i(x0 + self.xpos, y1 + self.ypos)
                        bgl.glEnd()
    
                    bgl.glBegin(bgl.GL_LINE_STRIP)
                    bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
                    bgl.glVertex2i(x1 + self.xpos, y0 + self.ypos)
                    bgl.glVertex2i(x1 + self.xpos, y1 + self.ypos)
                    bgl.glVertex2i(x0 + self.xpos, y1 + self.ypos)
                    bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
                    bgl.glEnd()
                    bgl.glPointSize(6)
    
                    bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 1.0)
                    bgl.glBegin(bgl.GL_POINTS)
                    bgl.glVertex2i(x0 + self.xpos, y0 + self.ypos)
                    bgl.glVertex2i(x1 + self.xpos, y0 + self.ypos)
                    bgl.glVertex2i(x1 + self.xpos, y1 + self.ypos)
                    bgl.glVertex2i(x0 + self.xpos, y1 + self.ypos)
                    bgl.glEnd()
    
                # Circle Cut
                if self.CutMode == CIRCLE:
                    DEG2RAD = 3.14159 / 180
                    v0 = mathutils.Vector((self.mouse_path[0][0], self.mouse_path[0][1], 0))
                    v1 = mathutils.Vector((self.mouse_path[1][0], self.mouse_path[1][1], 0))
                    v0 -= v1
                    radius = self.mouse_path[1][0] - self.mouse_path[0][0]
                    DEG2RAD = 3.14159 / (180.0 / self.stepAngle[self.step])
                    if self.ctrl:
                        self.stepR = (self.mouse_path[1][1] - self.mouse_path[0][1]) / 25
                        shift = (3.14159 / (360.0 / 60.0)) * int(self.stepR)
                    else:
                        shift = (self.mouse_path[1][1] - self.mouse_path[0][1]) / 50
    
                    if self.shift or self.CreateMode:
                        bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 0.5)
                        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
                        bgl.glVertex2f(x0 + self.xpos, y0 + self.ypos)
                        for i in range(0, int(360 / self.stepAngle[self.step])):
                            degInRad = i * DEG2RAD
                            bgl.glVertex2f(x0 + self.xpos + math.cos(degInRad + shift) * radius,
                                           y0 + self.ypos + math.sin(degInRad + shift) * radius)
                        bgl.glVertex2f(x0 + self.xpos + math.cos(0 + shift) * radius,
                                       y0 + self.ypos + math.sin(0 + shift) * radius)
                        bgl.glEnd()
    
                    bgl.glColor4f(UIColor[0], UIColor[1], UIColor[2], 1.0)
                    bgl.glBegin(bgl.GL_LINE_LOOP)
                    for i in range(0, int(360 / self.stepAngle[self.step])):
                        degInRad = i * DEG2RAD
                        bgl.glVertex2f(x0 + self.xpos + math.cos(degInRad + shift) * radius,
                                       y0 + self.ypos + math.sin(degInRad + shift) * radius)
                    bgl.glEnd()
    
        if self.ObjectMode or self.ProfileMode:
            if self.ShowCursor:
                region = context.region
                rv3d = context.space_data.region_3d
                view_width = context.region.width
    
                if self.ObjectMode:
                    ob = self.ObjectBrush
                if self.ProfileMode:
                    ob = self.ProfileBrush
                mat = ob.matrix_world
    
                # 50% alpha, 2 pixel width line
                bgl.glEnable(bgl.GL_BLEND)
    
                bbox = [mat * mathutils.Vector(b) for b in ob.bound_box]
    
                if self.shift:
                    bgl.glLineWidth(4)
                    bgl.glColor4f(0.5, 1.0, 0.0, 1.0)
                else:
                    bgl.glLineWidth(2)
                    bgl.glColor4f(1.0, 0.8, 0.0, 1.0)
                bgl.glBegin(bgl.GL_LINE_STRIP)
                idx = 0
                CRadius = ((bbox[7] - bbox[0]).length) / 2
                for i in range(int(len(self.CLR_C) / 3)):
                    vector3d = (self.CLR_C[idx * 3] * CRadius + self.CurLoc.x, self.CLR_C[idx * 3 + 1]
                                * CRadius + self.CurLoc.y, self.CLR_C[idx * 3 + 2] * CRadius + self.CurLoc.z)
                    vector2d = bpy_extras.view3d_utils.location_3d_to_region_2d(region, rv3d, vector3d)
                    if vector2d is not None:
                        bgl.glVertex2f(*vector2d)
                    idx += 1
                bgl.glEnd()
    
                bgl.glLineWidth(1)
                bgl.glDisable(bgl.GL_BLEND)
                bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    
                # Object display
                if self.qRot is not None:
                    ob.location = self.CurLoc
    
                    v = mathutils.Vector()
                    v.x = v.y = 0.0
                    v.z = self.BrushDepthOffset
                    ob.location += self.qRot * v
    
    1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    
                    e = mathutils.Euler()
                    e.x = 0.0
                    e.y = 0.0
                    e.z = self.aRotZ / 25.0
    
                    qe = e.to_quaternion()
                    qRot = self.qRot * qe
                    ob.rotation_mode = 'QUATERNION'
                    ob.rotation_quaternion = qRot
                    ob.rotation_mode = 'XYZ'
    
                    if self.ProfileMode:
                        if self.ProfileBrush is not None:
                            self.ProfileBrush.location = self.CurLoc
                            self.ProfileBrush.rotation_mode = 'QUATERNION'
                            self.ProfileBrush.rotation_quaternion = qRot
                            self.ProfileBrush.rotation_mode = 'XYZ'
    
        # Opengl defaults
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        bgl.glDisable(bgl.GL_POINT_SMOOTH)
    
    
    # Intersection
    # intersection function (ideasman42)
    def isect_line_plane_v3(p0, p1, p_co, p_no, epsilon=1e-6):
        """
        p0, p1: define the line
        p_co, p_no: define the plane:
            p_co is a point on the plane (plane coordinate).
            p_no is a normal vector defining the plane direction; does not need to be normalized.
    
        return a Vector or None (when the intersection can't be found).
        """
    
        u = sub_v3v3(p1, p0)
        dot = dot_v3v3(p_no, u)
    
        if abs(dot) > epsilon:
            # the factor of the point between p0 -> p1 (0 - 1)
            # if 'fac' is between (0 - 1) the point intersects with the segment.
            # otherwise:
            #  < 0.0: behind p0.
            #  > 1.0: infront of p1.
            w = sub_v3v3(p0, p_co)
            fac = -dot_v3v3(p_no, w) / dot
            u = mul_v3_fl(u, fac)
            return add_v3v3(p0, u)
        else:
            # The segment is parallel to plane
            return None
    
    # ----------------------
    # generic math functions
    
    
    def add_v3v3(v0, v1):
        return (
            v0[0] + v1[0],
            v0[1] + v1[1],
            v0[2] + v1[2],
        )
    
    
    def sub_v3v3(v0, v1):
        return (
            v0[0] - v1[0],
            v0[1] - v1[1],
            v0[2] - v1[2],
        )
    
    
    def dot_v3v3(v0, v1):
        return (
            (v0[0] * v1[0]) +
            (v0[1] * v1[1]) +
            (v0[2] * v1[2])
        )
    
    
    def len_squared_v3(v0):
        return dot_v3v3(v0, v0)
    
    
    def mul_v3_fl(v0, f):
        return (
            v0[0] * f,
            v0[1] * f,
            v0[2] * f,
        )
    
    # Cut Square
    
    
    def CreateCutSquare(self, context):
        FAR_LIMIT = 10000.0
    
        # New mesh
        me = bpy.data.meshes.new('CMT_Square')
    
        # New object
        ob = bpy.data.objects.new('CMT_Square', me)
        # Save new object
        self.CurrentObj = ob
        # Scene informations
        scene = context.scene
        region = context.region
        rv3d = context.region_data
        coord = self.mouse_path[0][0], self.mouse_path[0][1]
    
        depthLocation = region_2d_to_vector_3d(region, rv3d, coord)
        self.ViewVector = depthLocation
        if self.snapCursor:
            PlanePoint = context.scene.cursor_location
        else:
            if self.OpsObj is not None:
                PlanePoint = self.OpsObj.location
            else:
                PlanePoint = mathutils.Vector((0.0, 0.0, 0.0))
    
        PlaneNormal = depthLocation
        PlaneNormalised = PlaneNormal.normalized()
        d = -PlanePoint.x * PlaneNormalised.x - PlanePoint.y * PlaneNormalised.y - PlanePoint.z * PlaneNormalised.z
    
        # Link object to scene
        context.scene.objects.link(ob)
    
        # New bmesh
        t_bm = bmesh.new()
        t_bm.from_mesh(me)
        # Convert in 3d space
        v0 = self.mouse_path[0][0] + self.xpos, self.mouse_path[0][1] + self.ypos
        v1 = self.mouse_path[1][0] + self.xpos, self.mouse_path[1][1] + self.ypos
        v2 = self.mouse_path[1][0] + self.xpos, self.mouse_path[0][1] + self.ypos
        v3 = self.mouse_path[0][0] + self.xpos, self.mouse_path[1][1] + self.ypos
        vec = region_2d_to_vector_3d(region, rv3d, v0)
        loc0 = region_2d_to_location_3d(region, rv3d, v0, vec)
    
        vec = region_2d_to_vector_3d(region, rv3d, v1)
        loc1 = region_2d_to_location_3d(region, rv3d, v1, vec)
    
        vec = region_2d_to_vector_3d(region, rv3d, v2)
        loc2 = region_2d_to_location_3d(region, rv3d, v2, vec)
    
        vec = region_2d_to_vector_3d(region, rv3d, v3)
        loc3 = region_2d_to_location_3d(region, rv3d, v3, vec)
        p0 = loc0
        p1 = loc0 + PlaneNormalised * FAR_LIMIT
        loc0 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
        p0 = loc1
        p1 = loc1 + PlaneNormalised * FAR_LIMIT
        loc1 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
        p0 = loc2
        p1 = loc2 + PlaneNormalised * FAR_LIMIT
        loc2 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
        p0 = loc3
        p1 = loc3 + PlaneNormalised * FAR_LIMIT
        loc3 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
    
        t_v0 = t_bm.verts.new(loc0)
        t_v1 = t_bm.verts.new(loc2)
        t_v2 = t_bm.verts.new(loc1)
        t_v3 = t_bm.verts.new(loc3)
    
        # Update vertices index
        t_bm.verts.index_update()
        # New faces
        t_face = t_bm.faces.new([t_v0, t_v1, t_v2, t_v3])
        # Set mesh
        t_bm.to_mesh(me)
    
    
    # Cut Line
    def CreateCutLine(self, context):
        FAR_LIMIT = 10000.0
    
        me = bpy.data.meshes.new('CMT_Line')
    
        ob = bpy.data.objects.new('CMT_Line', me)
        self.CurrentObj = ob
    
        scene = context.scene
        region = context.region
        rv3d = context.region_data
        coord = self.mouse_path[0][0], self.mouse_path[0][1]
        depthLocation = region_2d_to_vector_3d(region, rv3d, coord)
        self.ViewVector = depthLocation
        if self.snapCursor:
            PlanePoint = context.scene.cursor_location
        else:
            PlanePoint = mathutils.Vector((0.0, 0.0, 0.0))
    
        PlaneNormal = depthLocation
        PlaneNormalised = PlaneNormal.normalized()
        d = -PlanePoint.x * PlaneNormalised.x - PlanePoint.y * PlaneNormalised.y - PlanePoint.z * PlaneNormalised.z
    
        context.scene.objects.link(ob)
    
        t_bm = bmesh.new()
        t_bm.from_mesh(me)
    
        FacesList = []
        NbVertices = 0
    
        bLine = False
    
        if (len(self.mouse_path) == 2) or ((len(self.mouse_path) <= 3) and (self.mouse_path[1] == self.mouse_path[2])):
            PlanePoint = mathutils.Vector((0.0, 0.0, 0.0))
            PlaneNormal = depthLocation
            PlaneNormalised = PlaneNormal.normalized()
            # Force rebool
            self.ForceRebool = True
            # It's a line
            bLine = True
            Index = 0
            for x, y in self.mouse_path:
                if Index < 2:
                    v0 = x + self.xpos, y + self.ypos
                    vec = region_2d_to_vector_3d(region, rv3d, v0)
                    loc0 = region_2d_to_location_3d(region, rv3d, v0, vec)
    
                    p0 = loc0
                    p1 = loc0 + PlaneNormalised * FAR_LIMIT
                    loc0 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
    
                    NbVertices += 1
                    Index += 1
                    if NbVertices == 1:
                        t_v0 = t_bm.verts.new(loc0)
                        t_init = t_v0
                        LocInit = loc0
                        t_bm.verts.index_update()
                    else:
                        t_v1 = t_bm.verts.new(loc0)
                        t_edges = t_bm.edges.new([t_v0, t_v1])
                        NbVertices = 1
                        t_v0 = t_v1
    
        else:
            for x, y in self.mouse_path:
                v0 = x + self.xpos, y + self.ypos
                vec = region_2d_to_vector_3d(region, rv3d, v0)
                loc0 = region_2d_to_location_3d(region, rv3d, v0, vec)
    
                p0 = loc0
                p1 = loc0 + PlaneNormalised * FAR_LIMIT
                loc0 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
    
                NbVertices += 1
                if NbVertices == 1:
                    t_v0 = t_bm.verts.new(loc0)
                    t_init = t_v0
                    LocInit = loc0
                    t_bm.verts.index_update()
                    FacesList.append(t_v0)
                else:
                    t_v1 = t_bm.verts.new(loc0)
                    t_edges = t_bm.edges.new([t_v0, t_v1])
                    FacesList.append(t_v1)
                    NbVertices = 1
                    t_v0 = t_v1
    
        if self.CreateMode:
            if self.Closed and (bLine == False):
                t_v1 = t_bm.verts.new(LocInit)
                t_edges = t_bm.edges.new([t_v0, t_v1])
                FacesList.append(t_v1)
                t_face = t_bm.faces.new(FacesList)
        else:
            if bLine == False:
                t_v1 = t_bm.verts.new(LocInit)
                t_edges = t_bm.edges.new([t_v0, t_v1])
                FacesList.append(t_v1)
                t_face = t_bm.faces.new(FacesList)
    
        t_bm.to_mesh(me)
    
    
    # Cut Circle
    def CreateCutCircle(self, context):
        FAR_LIMIT = 10000.0
    
        me = bpy.data.meshes.new('CMT_Circle')
    
        ob = bpy.data.objects.new('CMT_Circle', me)
        self.CurrentObj = ob
    
        scene = context.scene
        region = context.region
        rv3d = context.region_data
        coord = self.mouse_path[0][0], self.mouse_path[0][1]
        depthLocation = region_2d_to_vector_3d(region, rv3d, coord)
        self.ViewVector = depthLocation
        if self.snapCursor:
            PlanePoint = context.scene.cursor_location
        else:
            PlanePoint = mathutils.Vector((0.0, 0.0, 0.0))
    
        PlaneNormal = depthLocation
        PlaneNormalised = PlaneNormal.normalized()
        d = -PlanePoint.x * PlaneNormalised.x - PlanePoint.y * PlaneNormalised.y - PlanePoint.z * PlaneNormalised.z
    
        context.scene.objects.link(ob)
    
        t_bm = bmesh.new()
        t_bm.from_mesh(me)
    
        x0 = self.mouse_path[0][0]
        y0 = self.mouse_path[0][1]
        x1 = self.mouse_path[1][0]
        y1 = self.mouse_path[1][1]
    
        v0 = mathutils.Vector((self.mouse_path[0][0], self.mouse_path[0][1], 0))
        v1 = mathutils.Vector((self.mouse_path[1][0], self.mouse_path[1][1], 0))
        v0 -= v1
        radius = self.mouse_path[1][0] - self.mouse_path[0][0]
        DEG2RAD = math.pi / (180.0 / self.stepAngle[self.step])
        if self.ctrl:
            self.stepR = (self.mouse_path[1][1] - self.mouse_path[0][1]) / 25
            shift = (math.pi / (360.0 / self.stepAngle[self.step])) * (self.stepR)
        else:
            shift = (self.mouse_path[1][1] - self.mouse_path[0][1]) / 50
    
        # Convert point in 3D Space
        FacesList = []
        for i in range(0, int(360.0 / self.stepAngle[self.step])):
            degInRad = i * DEG2RAD
            v0 = x0 + self.xpos + math.cos(degInRad + shift) * radius, y0 + self.ypos + math.sin(degInRad + shift) * radius
            vec = region_2d_to_vector_3d(region, rv3d, v0)
            loc0 = region_2d_to_location_3d(region, rv3d, v0, vec)
    
            p0 = loc0
            p1 = loc0 + PlaneNormalised * FAR_LIMIT
            loc0 = isect_line_plane_v3(p0, p1, PlanePoint, PlaneNormalised)
    
            t_v0 = t_bm.verts.new(loc0)
    
            FacesList.append(t_v0)
    
        t_bm.verts.index_update()
    
        t_face = t_bm.faces.new(FacesList)
    
        t_bm.to_mesh(me)
    
    
    # Object dimensions (SCULPT Tools tips)
    def objDiagonal(obj):
        return ((obj.dimensions[0]**2) + (obj.dimensions[1]**2) + (obj.dimensions[2]**2))**0.5
    
    
    # Bevel Update
    def update_bevel(context):
        selection = context.selected_objects.copy()
        active = context.active_object
    
        if len(selection) > 0:
            for obj in selection:
                bpy.ops.object.select_all(action='DESELECT')
                obj.select = True
                context.scene.objects.active = obj
    
                # Test object name
                if obj.data.name.startswith("S_") or obj.data.name.startswith("S "):
                    bpy.ops.object.mode_set(mode='EDIT')
                    bpy.ops.mesh.region_to_loop()
                    bpy.ops.transform.edge_bevelweight(value=1)
                    bpy.ops.object.mode_set(mode='OBJECT')
                else:
                    act_bevel = False
                    for mod in obj.modifiers:
                        if mod.type == 'BEVEL':
                            act_bevel = True
                    if act_bevel:
                        context.scene.objects.active = bpy.data.objects[obj.name]
                        active = obj
    
                        bpy.ops.object.mode_set(mode='EDIT')
    
                        # Edge mode
                        bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='EDGE')
    
                        # Clear all
                        bpy.ops.mesh.select_all(action='SELECT')
                        bpy.ops.mesh.mark_sharp(clear=True)
                        bpy.ops.transform.edge_crease(value=-1)
    
                        bpy.ops.transform.edge_bevelweight(value=-1)
                        bpy.ops.mesh.select_all(action='DESELECT')
                        bpy.ops.mesh.edges_select_sharp(sharpness=0.523599)
                        bpy.ops.mesh.mark_sharp()
                        bpy.ops.transform.edge_crease(value=1)
                        bpy.ops.mesh.select_all(action='DESELECT')
                        bpy.ops.mesh.edges_select_sharp(sharpness=0.523599)
                        bpy.ops.transform.edge_bevelweight(value=1)
                        bpy.ops.mesh.select_all(action='DESELECT')
    
                        bpy.ops.object.mode_set(mode="OBJECT")
    
                        active.data.use_customdata_edge_bevel = True
    
                        for i in range(len(active.data.edges)):
                            if active.data.edges[i].select == True:
                                active.data.edges[i].bevel_weight = 1.0
                                active.data.edges[i].use_edge_sharp = True
    
                        Already = False
                        for m in active.modifiers:
                            if m.name == 'Bevel':
                                Already = True
    
                        if Already == False:
                            bpy.ops.object.modifier_add(type='BEVEL')
                            mod = context.object.modifiers[-1]
                            mod.limit_method = 'WEIGHT'
                            mod.width = 0.01
                            mod.profile = 0.699099
                            mod.use_clamp_overlap = False
                            mod.segments = 3
                            mod.loop_slide = False
    
                        bpy.ops.object.shade_smooth()
    
                        context.object.data.use_auto_smooth = True
                        context.object.data.auto_smooth_angle = 1.0472
    
        bpy.ops.object.select_all(action='DESELECT')
    
        for obj in selection:
            obj.select = True
        context.scene.objects.active = active
    
    # Create bevel
    
    
    def CreateBevel(context, CurrentObject):
        # Save active object
        SavActive = context.active_object
        # Active "CurrentObject"
        context.scene.objects.active = CurrentObject
    
        bpy.ops.object.mode_set(mode='EDIT')
    
        # Edge mode
        bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='EDGE')
    
        # Clear all
        bpy.ops.mesh.select_all(action='SELECT')
        bpy.ops.mesh.mark_sharp(clear=True)
        bpy.ops.transform.edge_crease(value=-1)
    
        bpy.ops.transform.edge_bevelweight(value=-1)
        bpy.ops.mesh.select_all(action='DESELECT')
        bpy.ops.mesh.edges_select_sharp(sharpness=0.523599)
        bpy.ops.mesh.mark_sharp()
        bpy.ops.transform.edge_crease(value=1)
        bpy.ops.mesh.select_all(action='DESELECT')
        bpy.ops.mesh.edges_select_sharp(sharpness=0.523599)
        bpy.ops.transform.edge_bevelweight(value=1)
        bpy.ops.mesh.select_all(action='DESELECT')
    
        bpy.ops.object.mode_set(mode="OBJECT")
    
        bpy.ops.object.mode_set(mode='OBJECT')
    
        Already = False
        for m in CurrentObject.modifiers:
            if m.name == 'Bevel':
                Already = True
    
        if Already == False:
            bpy.ops.object.modifier_add(type='BEVEL')
            mod = context.object.modifiers[-1]
            mod.limit_method = 'WEIGHT'
            mod.width = 0.01
            mod.profile = 0.699099
            mod.use_clamp_overlap = False
            mod.segments = 3
            mod.loop_slide = False
    
        bpy.ops.object.shade_smooth()
    
        context.object.data.use_auto_smooth = True
        context.object.data.auto_smooth_angle = 1.0471975
    
        # Remet l'objet actif par défaut
        context.scene.objects.active = SavActive
    
    
    # Picking (template)
    def Picking(context, event):
        # get the context arguments
        scene = context.scene
        region = context.region
        rv3d = context.region_data
        coord = event.mouse_region_x, event.mouse_region_y
    
        # get the ray from the viewport and mouse
        view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
        ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
    
        ray_target = ray_origin + view_vector
    
        def visible_objects_and_duplis():
            for obj in context.visible_objects:
                if obj.type == 'MESH':
                    yield (obj, obj.matrix_world.copy())
    
                if obj.dupli_type != 'NONE':
                    obj.dupli_list_create(scene)
                    for dob in obj.dupli_list:
                        obj_dupli = dob.object
                        if obj_dupli.type == 'MESH':
                            yield (obj_dupli, dob.matrix.copy())
    
                obj.dupli_list_clear()
    
        def obj_ray_cast(obj, matrix):
            # get the ray relative to the object
            matrix_inv = matrix.inverted()
            ray_origin_obj = matrix_inv * ray_origin
            ray_target_obj = matrix_inv * ray_target
            ray_direction_obj = ray_target_obj - ray_origin_obj
            # cast the ray
            success, location, normal, face_index = obj.ray_cast(ray_origin_obj, ray_direction_obj)
            if success:
                return location, normal, face_index
            else:
                return None, None, None
    
        # cast rays and find the closest object
        best_length_squared = -1.0
        best_obj = None
    
        # cast rays and find the closest object
        for obj, matrix in visible_objects_and_duplis():
            if obj.type == 'MESH':
                hit, normal, face_index = obj_ray_cast(obj, matrix)
                if hit is not None:
                    hit_world = matrix * hit
                    length_squared = (hit_world - ray_origin).length_squared
                    if best_obj is None or length_squared < best_length_squared:
                        scene.cursor_location = hit_world
                        best_length_squared = length_squared
                        best_obj = obj
                else:
                    if best_obj is None:
                        depthLocation = region_2d_to_vector_3d(region, rv3d, coord)
                        loc = region_2d_to_location_3d(region, rv3d, coord, depthLocation)
                        scene.cursor_location = loc
    
    
    def CreatePrimitive(self, _AngleStep, _radius):
        CLRaw = []
        Angle = 0.0
        self.NbPointsInPrimitive = 0
        while(Angle < 360.0):
            self.CircleListRaw.append(math.cos(math.radians(Angle)) * _radius)
            self.CircleListRaw.append(math.sin(math.radians(Angle)) * _radius)
            self.CircleListRaw.append(0.0)
            Angle += _AngleStep
            self.NbPointsInPrimitive += 1
        self.CircleListRaw.append(math.cos(math.radians(0.0)) * _radius)
        self.CircleListRaw.append(math.sin(math.radians(0.0)) * _radius)
        self.CircleListRaw.append(0.0)
        self.NbPointsInPrimitive += 1
    
    
    def MoveCursor(qRot, location, self):
        if qRot is not None:
            self.CLR_C.clear()
            vc = mathutils.Vector()
            idx = 0
            for i in range(int(len(self.CircleListRaw) / 3)):
                vc.x = self.CircleListRaw[idx * 3] * self.CRadius
                vc.y = self.CircleListRaw[idx * 3 + 1] * self.CRadius
                vc.z = self.CircleListRaw[idx * 3 + 2] * self.CRadius
                vc = qRot * vc
                self.CLR_C.append(vc.x)
                self.CLR_C.append(vc.y)
                self.CLR_C.append(vc.z)
                idx += 1
    
    
    def RBenVe(Object, Dir):
        ObjectV = Object.normalized()
        DirV = Dir.normalized()
        cosTheta = ObjectV.dot(DirV)
        rotationAxis = mathutils.Vector((0.0, 0.0, 0.0))
        if (cosTheta < -1 + 0.001):
            v = mathutils.Vector((0.0, 1.0, 0.0))
            rotationAxis = ObjectV.cross(v)
            rotationAxis = rotationAxis.normalized()
            q = mathutils.Quaternion()
            q.w = 0.0
            q.x = rotationAxis.x
            q.y = rotationAxis.y
            q.z = rotationAxis.z
            return q
        rotationAxis = ObjectV.cross(DirV)
        s = math.sqrt((1.0 + cosTheta) * 2.0)
        invs = 1 / s
        q = mathutils.Quaternion()
        q.w = s * 0.5
        q.x = rotationAxis.x * invs
        q.y = rotationAxis.y * invs
        q.z = rotationAxis.z * invs
        return q
    
    
    def Pick(context, event, self, ray_max=10000.0):
        scene = context.scene
        region = context.region
        rv3d = context.region_data
        coord = event.mouse_region_x, event.mouse_region_y
        view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
        ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
        ray_target = ray_origin + (view_vector * ray_max)
    
        def obj_ray_cast(obj, matrix):
            matrix_inv = matrix.inverted()
            ray_origin_obj = matrix_inv * ray_origin
            ray_target_obj = matrix_inv * ray_target
            success, hit, normal, face_index = obj.ray_cast(ray_origin_obj, ray_target_obj)
            if success:
                return hit, normal, face_index
            else:
                return None, None, None
    
        best_length_squared = ray_max * ray_max
        best_obj = None
        for obj in self.CList:
            matrix = obj.matrix_world
            hit, normal, face_index = obj_ray_cast(obj, matrix)
    
            rotation = obj.rotation_euler.to_quaternion()
    
            if hit is not None:
                hit_world = matrix * hit
                length_squared = (hit_world - ray_origin).length_squared
                if length_squared < best_length_squared:
                    best_length_squared = length_squared
                    best_obj = obj
                    hits = hit_world
                    ns = normal
                    fs = face_index
    
        if best_obj is not None:
    
            return hits, ns, fs, rotation
    
        else:
            return None, None, None
    
    
    def SelectObject(self, copyobj):
        copyobj.select = True
    
        for child in copyobj.children:
            SelectObject(self, child)
    
        if copyobj.parent is None:
            bpy.context.scene.objects.active = copyobj
    
    
    # Undo
    def printUndo(self):
        for l in self.UList:
            print(l)
    
    
    def UndoAdd(self, type, OpsObj):
        if OpsObj is None:
            return
        if type != "DUPLICATE":
            ob = OpsObj
            # Creation du mesh de 'sauvegarde'
            bm = bmesh.new()
            bm.from_mesh(ob.data)
    
            self.UndoOps.append((OpsObj, type, bm))
        else:
            self.UndoOps.append((OpsObj, type, None))
    
    
    def UndoListUpdate(self):
        self.UList.append((self.UndoOps.copy()))
        self.UList_Index += 1
        self.UndoOps.clear()
    
    
    def Undo(self):
        if self.UList_Index < 0:
            return
        # get previous mesh
        for o in self.UList[self.UList_Index]:
            if o[1] == "MESH":
                bm = o[2]
                bm.to_mesh(o[0].data)
    
        SelectObjList = bpy.context.selected_objects.copy()
        Active_Obj = bpy.context.active_object
        bpy.ops.object.select_all(action='TOGGLE')
    
        for o in self.UList[self.UList_Index]:
            if o[1] == "REBOOL":
                o[0].select = True
                o[0].hide = False
    
            if o[1] == "DUPLICATE":
                o[0].select = True
                o[0].hide = False
    
        bpy.ops.object.delete(use_global=False)
    
        for so in SelectObjList:
            bpy.data.objects[so.name].select = True
        bpy.context.scene.objects.active = Active_Obj
    
        self.UList_Index -= 1
        self.UList[self.UList_Index + 1:] = []
    
    
    def duplicateObject(self):
        if self.Instantiate:
            bpy.ops.object.duplicate_move_linked(
                OBJECT_OT_duplicate={
                    "linked": True,
                    "mode": 'TRANSLATION',
                },
                TRANSFORM_OT_translate={
                    "value": (0, 0, 0),
                },
            )
        else:
            bpy.ops.object.duplicate_move(
                OBJECT_OT_duplicate={
                    "linked": False,
                    "mode": 'TRANSLATION',
                },
                TRANSFORM_OT_translate={
                    "value": (0, 0, 0),
                },
            )
    
        ob_new = bpy.context.active_object
    
        ob_new.location = self.CurLoc
    
        v = mathutils.Vector()
        v.x = v.y = 0.0
        v.z = self.BrushDepthOffset