1. 概述

坐标数据是空间数据文件的核心,空间数据的数据量往往是很大的。数据可视化是GIS的一个核心应用,绘制海量的坐标数据始终是一个考验设备性能的难题,使用GPU进行绘制可有效减少CPU的负载,提升绘制时的速度

shapefile是空间数据文件常用的格式,Shapefile C Library(也叫shapelib)提供了编写简单的 C/C++ 程序以读取、写入和更新ESRI Shapefile 以及关联的属性文件 (.dbf) 的功能

shapelib的官网:Shapefile C Library (maptools.org)

shapelib的GitHub地址:OSGeo/shapelib: Official repository of shapelib (github.com)

本文基于C++语言,使用shapelib库来读取shp文件,并使用基于GLFW和GLAD来使用OpenGL绘制空间数据

2. 环境准备

本文的系统环境为Ubuntu 20.04.3 LTS,关于C++语言的OpenGL环境搭建可参考:

shapelib在Linux上安装参考其GitHub指导:

具体步骤为:

  • $ git clone https://github.com/OSGeo/shapelib.git
  • $ cmake build .
  • $ make
  • $ make install

Windows平台上的安装可以参考:

本文使用的数据为云南的县界,数据信息如图所示:

注意:

  • 本文数据编码是UTF-8
  • 本文数据Geometry是Polygon
  • 本文数据坐标系是投影坐标系

3. 读取shp文件

参考博客:

官方API文档:

这里笔者需要读取shp文件的四至范围和每个Geometry的坐标数据

代码如下:

#include <shapefil.h>

int main()
{
//读取shp
const char * pszShapeFile = "../云南县界/云南县界.shp";
SHPHandle hShp= SHPOpen(pszShapeFile, "r");
int nShapeType, nVertices;
int nEntities = 0;
double* minB = new double[4];
double* maxB = new double[4];
SHPGetInfo(hShp, &nEntities, &nShapeType, minB, maxB);
printf("ShapeType:%d\n", nShapeType);
printf("Entities:%d\n", nEntities);
printf("Xmin, Ymin: %f,%f\n", minB[0], minB[1]);
printf("Xmax, Ymax: %f,%f\n", maxB[0], maxB[1]);
for (int i = 0; i < nEntities;i++)
{
int iShape = i;
SHPObject *obj = SHPReadObject(hShp, iShape);
printf("--------------Feature:%d------------\n",iShape);
int parts = obj->nParts;
int verts=obj->nVertices;
printf("nParts:%d\n", parts);
printf("nVertices:%d\n", verts);
for (size_t i = 0; i < verts; i++)
{
double x=obj->padfX[i];
double y = obj->padfY[i];
printf("%f,%f;", x,y);
}
printf("\n");
}
SHPClose(hShp);
}

结果输出:

Xmin, Ymin: 348122 2.34118e+06
Xmax, Ymax: 1.23349e+06 3.23468e+06
ShapeType:5
Entities:125
......

4. OpenGL绘制

OpenGL的绘制流程参考:

该网站上绘制两个三角形的示例代码:

本文所使用的方法是每个Geometry绑定一个VAO和VBO,然后进行绘制

全部代码如下:

#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <shapefil.h>
#include <vector>
#include <iostream> void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *window); // settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
double XMAX, YMAX, XMIN, YMIN;
std::vector<int> size; const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0"; int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif // glfw window creation
// --------------------
GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
} // build and compile our shader program
// ------------------------------------
// vertex shader
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n"
<< infoLog << std::endl;
}
// fragment shader
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n"
<< infoLog << std::endl;
}
// link shaders
unsigned int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n"
<< infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader); const char *pszShapeFile = "../云南县界/云南县界.shp";
SHPHandle hShp = SHPOpen(pszShapeFile, "r");
int nShapeType, nVertices;
int nEntities = 0;
double *minB = new double[4];
double *maxB = new double[4];
SHPGetInfo(hShp, &nEntities, &nShapeType, minB, maxB);
std::cout <<"Xmin, Ymin: "<< minB[0] << " " << minB[1] << std::endl;
std::cout <<"Xmax, Ymax: "<< maxB[0] << " " << maxB[1] << std::endl;
XMAX = maxB[0];
XMIN = minB[0];
YMAX = maxB[1];
YMIN = minB[1];
printf("ShapeType:%d\n", nShapeType);
printf("Entities:%d\n", nEntities); unsigned int VBOs[nEntities], VAOs[nEntities];
glGenVertexArrays(nEntities, VAOs); // we can also generate multiple VAOs or buffers at the same time
glGenBuffers(nEntities, VBOs);
for (int i = 0; i < nEntities; i++)
{
std::vector<double> arr;
int iShape = i;
SHPObject *obj = SHPReadObject(hShp, iShape);
// printf("--------------Feature:%d------------\n",iShape);
int parts = obj->nParts;
int verts = obj->nVertices;
// printf("nParts:%d\n", parts);
// printf("nVertices:%d\n", verts);
for (size_t i = 0; i < verts; i++)
{
double x = (obj->padfX[i] - XMIN) / (XMAX - XMIN) * 2 - 1;
double y = (obj->padfY[i] - YMIN) / (YMAX - YMIN) * 2 - 1;
// double x = obj->padfX[i];
// double y = obj->padfY[i];
// printf("%f,%f;", x, y);
arr.push_back(x);
arr.push_back(y);
arr.push_back(0.0f);
} size.push_back(arr.size()/3);
double vertices[arr.size()];
std::copy(arr.begin(), arr.end(), vertices); glBindVertexArray(VAOs[i]);
glBindBuffer(GL_ARRAY_BUFFER, VBOs[i]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, 3 * sizeof(double), (void *)0); // Vertex attributes stay the same
glEnableVertexAttribArray(0);
}
SHPClose(hShp); // uncomment this call to draw in wireframe polygons.
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window); // render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram);
for (int i = 0; i < size.size(); i++)
{
glBindVertexArray(VAOs[i]);
glDrawArrays(GL_LINE_STRIP, 0, size[i]);
// std::cout<<VAOs[i]<<" "<<size[i]<<std::endl;
} // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
} // optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(size.size(), VAOs);
glDeleteBuffers(size.size(), VBOs);
glDeleteProgram(shaderProgram); // glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
} // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
} // glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}

本文基于CMake构建,CMakeLists.txt代码如下:

# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8) # 项目信息
project (Demo) # 查找当前目录下的所有源文件
# 并将名称保存到 DIR_SRCS 变量
# aux_source_directory(.. DIR_SRCS) find_package(shapelib)
find_package(glfw3 REQUIRED)
find_package( OpenGL REQUIRED )
include_directories( ${OPENGL_INCLUDE_DIRS} ) # 指定生成目标
# add_executable(Demo ${DIR_SRCS})
add_executable(Demo ../glad.c ../shapelib_opengl.cpp) target_link_libraries(${PROJECT_NAME} ${shapelib_LIBRARIES} ${OPENGL_LIBRARIES} glfw)

注意

  • shapelib_opengl.cpp是上述代码的文件名

构建:

$ cmake build .

编译:

$ make

运行:

./Demo

结果如图所示:

5. 参考资料

[1]OSGeo/shapelib: Official repository of shapelib (github.com)

[2]Shapefile C Library (maptools.org)

[3]shapelib库 VS2017X64编译并调用 | 码农家园 (codenong.com)

[4]GIS开源库shapeLib的使用方法(一) - cjingzm - 博客园 (cnblogs.com)

[5][Shapefile C Library]读写shp图形(C++&.net Wapper) - 归山须尽丘壑美 - 博客园 (cnblogs.com)

[6]你好,三角形 - LearnOpenGL CN (learnopengl-cn.github.io)

使用Shapefile C Library读取shp文件并使用OpenGL绘制的更多相关文章

  1. [Shapefile C Library]读取shp图形(.net Wapper)

    ShapeLib的.net Wapper版可以在官网下载到,在WorldWind中也有使用.ORG据说也是使用的ShapeLib实现的shp文件的读写. 官网:http://shapelib.mapt ...

  2. C#读取shp文件并获取图形保存到sde要素类中(不使用ESRI的类库,纯c#实现)

    说明:首先要将sde要素类发布成对应的要素服务,通过对要素服务的操作,实现数据在sde要素类中的增删 //向服务器发出请求 public string getPostData(string postS ...

  3. [Shapefile C Library]读写shp图形(C++&.net Wapper)

    ShapeLib的.net Wapper版可以在官网下载到,在WorldWind中也有使用.ORG据说也是使用的ShapeLib实现的shp文件的读写. 官网:http://shapelib.mapt ...

  4. GeoJson的生成与解析,JSON解析,Java读写geojson,geotools读取shp文件,Geotools中Geometry对象与GeoJson的相互转换

    GeoJson的生成与解析 一.wkt格式的geometry转成json格式 二.json格式转wkt格式 三.json格式的数据进行解析 四.Java读写geojson 五.geotools读取sh ...

  5. mfc通过MapWinGIS控件读取shp文件(通过#import实现)

    在MFC工程中想使用MapWinGIS组件,有多种方法可以实现, 第一种方法,#Import来实现 1.首先注册MapWinGIS ActiveX组件, 2.新建一个单文档工程:MapGis,为控件添 ...

  6. GeoTools介绍、环境安装、读取shp文件并显示

    GeoTools是一个开放源代码(LGPL)Java代码库,它提供了符合标准的方法来处理地理空间数据,例如实现地理信息系统(GIS).GeoTools库实现了开放地理空间联盟(OGC)规范. Geot ...

  7. arcgis for android 读取shp文件中文乱码解决方法

    设置注册表默认字符,即可解决中文乱码问题. 'dbfDefault' 设置方法1.开始--运行,输入”Regedit“,打开注册表.2.如是用的是 10.x 版本 ArcGIS Desktop,定位到 ...

  8. mfc通过MapWinGIS控件读取shp文件(不通过#import实现)

    1.首先注册MapWinGIS ActiveX组件, 引入MapWinGIS.ocx产生的MapWinGIS_i.h和MapWinGIS_i.c文件,利用CoCreateInstance函数来调用 演 ...

  9. 结合C++和GDAL实现shapefile(shp)文件的读取

    工具:vs2012+GDAL 2.0 数据:中国省界SHP文件bou2_4p.shp   可点击下载 包含头文件: #include "ogrsf_frmts.h" 代码: int ...

  10. C#、C++用GDAL读shp文件(转载)

    C#.C++用GDAL读shp文件 C#用GDAL读shp文件 (2012-08-14 17:09:45) 标签: 杂谈 分类: c#方面的总结 1.目前使用开发环境为VS2008+GDAL1.81 ...

随机推荐

  1. 【每日一题】【DFS/回溯】2022年1月1日-113. 路径总和 II

    给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径. 叶子节点 是指没有子节点的节点. 来源:力扣(LeetCode)链接 ...

  2. 微软宣布 S2C2F 已被 OpenSSF 采用

    开源供应链安全对大多数 IT 领导者来说是个日益严峻的挑战,围绕确保开发人员在构建软件时如何使用和管理开源软件 (OSS) 依赖项的稳健策略至关重要.Microsoft 发布安全供应链消费框架 (S2 ...

  3. python前言

    目录 一.typora软件以及markdown语法介绍 1.输入标题的两种方法 2.无序列表 3.有序列表 4.在typora里插入多行代码块 5.制作表格 6.表情包 7.链接 8.Typora查看 ...

  4. uniapp微信小程序 原生底部导航栏

    在pages.json文件中写  "tabBar": { "color": "#333333", "selectedColor&q ...

  5. Python实验报告(第7章)

    实验7:面向对象程序设计 一.实验目的和要求 1.了解面向对象的基本概念(对象.类.构造方法): 2.学会类的定义和使用: 3.掌握属性的创建和修改: 4.掌握继承的基本语法. 二.实验环境 软件版本 ...

  6. Spark框架下均值漂移算法对舆情聚类的分析

    知网链接 原文链接 张京坤,  王怡怡 软件导刊   2022年21卷第6期 页码:141-146 DOI:10.11907/rjdk.211889    中图分类号:TP274 纸质出版日期:202 ...

  7. GIS数据下载合集:遥感、土壤、气象、行政区数据...

      本文介绍GIS领域相关的各类综合数据免费获取网站,包括遥感数据.气象数据.土地数据.土壤数据.农业数据.行政区数据.社会数据.经济数据等等.   数据较多,大家可以直接通过下方目录加以总览:点击数 ...

  8. Python 内置界面开发框架 Tkinter入门篇 乙

    本文大概 1685 个字,阅读需花 6 分钟内容不多, 但也花了一些精力如要交流, 欢迎关注我然后评论区留言 谢谢你的点赞收藏分享 这篇文章属于系列文章<Python 内置界面开发框架 Tkin ...

  9. JSP第五次作业

    1.教材P78-79  例4-9 1 <%@ page language="java" import="java.util.*" pageEncoding ...

  10. 翻译《threejsfundamentals》离屏渲染+web-worker一篇

    Three.js OffscreenCanvas    OffscreenCanvas是一种相对较新的浏览器功能,目前仅在Chrome中可用,但显然也即将适用于其他浏览器. OffscreenCanv ...